difftreelog
Merge pull request #113 from usetech-llc/feature/NFTPAR-196_sponsor_setVariableMetadata
in: master
Sponsored setVariableMetadata
19 files changed
node/src/chain_spec.rsdiffbeforeafterboth--- a/node/src/chain_spec.rs
+++ b/node/src/chain_spec.rs
@@ -180,9 +180,9 @@
.collect(),
}),
pallet_nft: Some(NftConfig {
- collection: vec![(
+ collection_id: vec![(
1,
- CollectionType {
+ Collection {
owner: get_account_id_from_seed::<sr25519::Public>("Alice"),
mode: CollectionMode::NFT,
access: AccessMode::Normal,
pallets/nft/src/default_weights.rsdiffbeforeafterboth--- a/pallets/nft/src/default_weights.rs
+++ b/pallets/nft/src/default_weights.rs
@@ -127,6 +127,11 @@
.saturating_add(DbWeight::get().reads(0 as Weight))
.saturating_add(DbWeight::get().writes(2 as Weight))
}
+ fn set_variable_meta_data_sponsoring_rate_limit() -> Weight {
+ (3_500_000 as Weight)
+ .saturating_add(DbWeight::get().reads(2 as Weight))
+ .saturating_add(DbWeight::get().writes(1 as Weight))
+ }
fn toggle_contract_white_list() -> Weight {
(3_000_000 as Weight)
.saturating_add(DbWeight::get().reads(0 as Weight))
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -13,6 +13,7 @@
#[cfg(feature = "std")]
pub use serde::*;
+use core::ops::{Deref, DerefMut};
use codec::{Decode, Encode};
pub use frame_support::{
construct_runtime, decl_event, decl_module, decl_storage, decl_error,
@@ -160,10 +161,10 @@
}
}
-#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
+#[derive(Encode, Decode, Clone, PartialEq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub struct CollectionType<AccountId> {
- pub owner: AccountId,
+pub struct Collection<T: Config> {
+ pub owner: T::AccountId,
pub mode: CollectionMode,
pub access: AccessMode,
pub decimal_points: DecimalPoints,
@@ -174,11 +175,30 @@
pub offchain_schema: Vec<u8>,
pub schema_version: SchemaVersion,
pub sponsorship: SponsorshipState<AccountId>,
- pub limits: CollectionLimits, // Collection private restrictions
+ pub limits: CollectionLimits<T::BlockNumber>, // Collection private restrictions
pub variable_on_chain_schema: Vec<u8>, //
pub const_on_chain_schema: Vec<u8>, //
}
+pub struct CollectionHandle<T: Config> {
+ pub id: CollectionId,
+ collection: Collection<T>,
+}
+
+impl<T: Config> Deref for CollectionHandle<T> {
+ type Target = Collection<T>;
+
+ fn deref(&self) -> &Self::Target {
+ &self.collection
+ }
+}
+
+impl<T: Config> DerefMut for CollectionHandle<T> {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.collection
+ }
+}
+
#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct NftItemType<AccountId> {
@@ -214,9 +234,13 @@
#[derive(Encode, Decode, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub struct CollectionLimits {
+pub struct CollectionLimits<BlockNumber: Encode + Decode> {
pub account_token_ownership_limit: u32,
pub sponsored_data_size: u32,
+ /// None - setVariableMetadata is not sponsored
+ /// Some(v) - setVariableMetadata is sponsored
+ /// if there is v block between txs
+ pub sponsored_data_rate_limit: Option<BlockNumber>,
pub token_limit: u32,
// Timeouts for item types in passed blocks
@@ -225,12 +249,13 @@
pub owner_can_destroy: bool,
}
-impl Default for CollectionLimits {
- fn default() -> CollectionLimits {
- CollectionLimits {
+impl<BlockNumber: Encode + Decode> Default for CollectionLimits<BlockNumber> {
+ fn default() -> Self {
+ Self {
account_token_ownership_limit: 10_000_000,
token_limit: u32::max_value(),
- sponsored_data_size: u32::MAX,
+ sponsored_data_size: u32::MAX,
+ sponsored_data_rate_limit: None,
sponsor_transfer_timeout: 14400,
owner_can_transfer: true,
owner_can_destroy: true
@@ -283,6 +308,7 @@
fn set_schema_version() -> Weight;
fn set_chain_limits() -> Weight;
fn set_contract_sponsoring_rate_limit() -> Weight;
+ fn set_variable_meta_data_sponsoring_rate_limit() -> Weight;
fn toggle_contract_white_list() -> Weight;
fn add_to_contract_white_list() -> Weight;
fn remove_from_contract_white_list() -> Weight;
@@ -496,7 +522,7 @@
//#region Basic collections
/// Collection info
/// Collection id (controlled?1)
- pub Collection get(fn collection) config(): map hasher(blake2_128_concat) CollectionId => CollectionType<T::AccountId>;
+ pub CollectionById get(fn collection_id) config(): map hasher(blake2_128_concat) CollectionId => Option<Collection<T>> = None;
/// List of collection admins
/// Collection id (controlled?2)
pub AdminList get(fn admin_list_collection): map hasher(blake2_128_concat) CollectionId => Vec<T::AccountId>;
@@ -538,6 +564,10 @@
pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;
//#endregion
+ /// Variable metadata sponsoring
+ /// Collection id (controlled?2), token id (controlled?2)
+ pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber> = None;
+
//#region Contract Sponsorship and Ownership
/// Contract address (real)
pub ContractOwner get(fn contract_owner): map hasher(twox_64_concat) T::AccountId => T::AccountId;
@@ -556,7 +586,7 @@
add_extra_genesis {
build(|config: &GenesisConfig<T>| {
// Modification of storage
- for (_num, _c) in &config.collection {
+ for (_num, _c) in &config.collection_id {
<Module<T>>::init_collection(_c);
}
@@ -710,7 +740,7 @@
};
// Create new collection
- let new_collection = CollectionType {
+ let new_collection = Collection {
owner: who.clone(),
name: collection_name,
mode: mode.clone(),
@@ -728,7 +758,7 @@
};
// Add new collection to map
- <Collection<T>>::insert(next_id, new_collection);
+ <CollectionById<T>>::insert(next_id, new_collection);
// call event
Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));
@@ -750,10 +780,9 @@
pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {
let sender = ensure_signed(origin)?;
- Self::check_owner_permissions(collection_id, sender)?;
-
- let target_collection = <Collection<T>>::get(collection_id);
- if !target_collection.limits.owner_can_destroy {
+ let collection = Self::get_collection(collection_id)?;
+ Self::check_owner_permissions(&collection, sender)?;
+ if !collection.limits.owner_can_destroy {
fail!(Error::<T>::NoPermission);
}
@@ -762,7 +791,7 @@
<Balance<T>>::remove_prefix(collection_id);
<ItemListIndex>::remove(collection_id);
<AdminList<T>>::remove(collection_id);
- <Collection<T>>::remove(collection_id);
+ <CollectionById<T>>::remove(collection_id);
<WhiteList<T>>::remove_prefix(collection_id);
<NftItemList<T>>::remove_prefix(collection_id);
@@ -773,6 +802,8 @@
<FungibleTransferBasket<T>>::remove_prefix(collection_id);
<ReFungibleTransferBasket<T>>::remove_prefix(collection_id);
+ <VariableMetaDataBasket<T>>::remove_prefix(collection_id);
+
DestroyedCollectionCount::put(DestroyedCollectionCount::get()
.checked_add(1)
.ok_or(Error::<T>::NumOverflow)?);
@@ -797,7 +828,8 @@
pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{
let sender = ensure_signed(origin)?;
- Self::check_owner_or_admin_permissions(collection_id, sender)?;
+ let collection = Self::get_collection(collection_id)?;
+ Self::check_owner_or_admin_permissions(&collection, sender)?;
<WhiteList<T>>::insert(collection_id, address, true);
@@ -821,7 +853,8 @@
pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{
let sender = ensure_signed(origin)?;
- Self::check_owner_or_admin_permissions(collection_id, sender)?;
+ let collection = Self::get_collection(collection_id)?;
+ Self::check_owner_or_admin_permissions(&collection, sender)?;
<WhiteList<T>>::remove(collection_id, address);
@@ -845,10 +878,10 @@
{
let sender = ensure_signed(origin)?;
- Self::check_owner_permissions(collection_id, sender)?;
- let mut target_collection = <Collection<T>>::get(collection_id);
+ let mut target_collection = Self::get_collection(collection_id)?;
+ Self::check_owner_permissions(&target_collection, sender)?;
target_collection.access = mode;
- <Collection<T>>::insert(collection_id, target_collection);
+ Self::save_collection(target_collection);
Ok(())
}
@@ -872,10 +905,10 @@
{
let sender = ensure_signed(origin)?;
- Self::check_owner_permissions(collection_id, sender)?;
- let mut target_collection = <Collection<T>>::get(collection_id);
+ let mut target_collection = Self::get_collection(collection_id)?;
+ Self::check_owner_permissions(&target_collection, sender)?;
target_collection.mint_mode = mint_permission;
- <Collection<T>>::insert(collection_id, target_collection);
+ Self::save_collection(target_collection);
Ok(())
}
@@ -896,10 +929,10 @@
pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {
let sender = ensure_signed(origin)?;
- Self::check_owner_permissions(collection_id, sender)?;
- let mut target_collection = <Collection<T>>::get(collection_id);
+ let mut target_collection = Self::get_collection(collection_id)?;
+ Self::check_owner_permissions(&target_collection, sender)?;
target_collection.owner = new_owner;
- <Collection<T>>::insert(collection_id, target_collection);
+ Self::save_collection(target_collection);
Ok(())
}
@@ -922,7 +955,8 @@
pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::AccountId) -> DispatchResult {
let sender = ensure_signed(origin)?;
- Self::check_owner_or_admin_permissions(collection_id, sender)?;
+ let collection = Self::get_collection(collection_id)?;
+ Self::check_owner_or_admin_permissions(&collection, sender)?;
let mut admin_arr: Vec<T::AccountId> = Vec::new();
if <AdminList<T>>::contains_key(collection_id)
@@ -957,7 +991,8 @@
pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::AccountId) -> DispatchResult {
let sender = ensure_signed(origin)?;
- Self::check_owner_or_admin_permissions(collection_id, sender)?;
+ let collection = Self::get_collection(collection_id)?;
+ Self::check_owner_or_admin_permissions(&collection, sender)?;
ensure!(<AdminList<T>>::contains_key(collection_id), Error::<T>::AdminNotFound);
let mut admin_arr = <AdminList<T>>::get(collection_id);
@@ -981,13 +1016,11 @@
pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {
let sender = ensure_signed(origin)?;
- ensure!(<Collection<T>>::contains_key(collection_id), Error::<T>::CollectionNotFound);
-
- let mut target_collection = <Collection<T>>::get(collection_id);
- ensure!(sender == target_collection.owner, Error::<T>::NoPermission);
+ let mut target_collection = Self::get_collection(collection_id)?;
+ Self::check_owner_permissions(&target_collection, sender)?;
target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor);
- <Collection<T>>::insert(collection_id, target_collection);
+ Self::save_collection(target_collection);
Ok(())
}
@@ -1004,16 +1037,15 @@
pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {
let sender = ensure_signed(origin)?;
- ensure!(<Collection<T>>::contains_key(collection_id), Error::<T>::CollectionNotFound);
- let mut target_collection = <Collection<T>>::get(collection_id);
+ let mut target_collection = Self::get_collection(collection_id)?;
ensure!(
target_collection.sponsorship.pending_sponsor() == Some(&sender),
Error::<T>::ConfirmUnsetSponsorFail
);
target_collection.sponsorship = SponsorshipState::Confirmed(sender);
- <Collection<T>>::insert(collection_id, target_collection);
+ Self::save_collection(target_collection);
Ok(())
}
@@ -1032,13 +1064,12 @@
pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {
let sender = ensure_signed(origin)?;
- ensure!(<Collection<T>>::contains_key(collection_id), Error::<T>::CollectionNotFound);
- let mut target_collection = <Collection<T>>::get(collection_id);
- ensure!(sender == target_collection.owner, Error::<T>::NoPermission);
+ let mut target_collection = Self::get_collection(collection_id)?;
+ Self::check_owner_permissions(&target_collection, sender)?;
target_collection.sponsorship = SponsorshipState::Disabled;
- <Collection<T>>::insert(collection_id, target_collection);
+ Self::save_collection(target_collection);
Ok(())
}
@@ -1072,14 +1103,12 @@
pub fn create_item(origin, collection_id: CollectionId, owner: T::AccountId, data: CreateItemData) -> DispatchResult {
let sender = ensure_signed(origin)?;
-
- Self::collection_exists(collection_id)?;
- let target_collection = <Collection<T>>::get(collection_id);
+ let target_collection = Self::get_collection(collection_id)?;
- Self::can_create_items_in_collection(collection_id, &target_collection, &sender, &owner, 1)?;
+ Self::can_create_items_in_collection(&target_collection, &sender, &owner, 1)?;
Self::validate_create_item_args(&target_collection, &data)?;
- Self::create_item_no_validation(collection_id, owner, data)?;
+ Self::create_item_no_validation(&target_collection, owner, data)?;
Ok(())
}
@@ -1111,16 +1140,15 @@
ensure!(items_data.len() > 0, Error::<T>::EmptyArgument);
let sender = ensure_signed(origin)?;
- Self::collection_exists(collection_id)?;
- let target_collection = <Collection<T>>::get(collection_id);
+ let target_collection = Self::get_collection(collection_id)?;
- Self::can_create_items_in_collection(collection_id, &target_collection, &sender, &owner, items_data.len() as u32)?;
+ Self::can_create_items_in_collection(&target_collection, &sender, &owner, items_data.len() as u32)?;
for data in &items_data {
Self::validate_create_item_args(&target_collection, data)?;
}
for data in &items_data {
- Self::create_item_no_validation(collection_id, owner.clone(), data.clone())?;
+ Self::create_item_no_validation(&target_collection, owner.clone(), data.clone())?;
}
Ok(())
@@ -1144,33 +1172,32 @@
pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {
let sender = ensure_signed(origin)?;
- Self::collection_exists(collection_id)?;
// Transfer permissions check
- let target_collection = <Collection<T>>::get(collection_id);
+ let target_collection = Self::get_collection(collection_id)?;
ensure!(
- Self::is_item_owner(sender.clone(), collection_id, item_id) ||
+ Self::is_item_owner(sender.clone(), &target_collection, item_id) ||
(
target_collection.limits.owner_can_transfer &&
- Self::is_owner_or_admin_permissions(collection_id, sender.clone())
+ Self::is_owner_or_admin_permissions(&target_collection, sender.clone())
),
Error::<T>::NoPermission
);
if target_collection.access == AccessMode::WhiteList {
- Self::check_white_list(collection_id, &sender)?;
+ Self::check_white_list(&target_collection, &sender)?;
}
match target_collection.mode
{
- CollectionMode::NFT => Self::burn_nft_item(collection_id, item_id)?,
- CollectionMode::Fungible(_) => Self::burn_fungible_item(&sender, collection_id, value)?,
- CollectionMode::ReFungible => Self::burn_refungible_item(collection_id, item_id, &sender)?,
+ CollectionMode::NFT => Self::burn_nft_item(&target_collection, item_id)?,
+ CollectionMode::Fungible(_) => Self::burn_fungible_item(&sender, &target_collection, value)?,
+ CollectionMode::ReFungible => Self::burn_refungible_item(&target_collection, item_id, &sender)?,
_ => ()
};
// call event
- Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));
+ Self::deposit_event(RawEvent::ItemDestroyed(target_collection.id, item_id));
Ok(())
}
@@ -1202,7 +1229,9 @@
#[transactional]
pub fn transfer(origin, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {
let sender = ensure_signed(origin)?;
- Self::transfer_internal(sender, recipient, collection_id, item_id, value)
+ let collection = Self::get_collection(collection_id)?;
+
+ Self::transfer_internal(sender, recipient, &collection, item_id, value)
}
/// Set, change, or remove approved address to transfer the ownership of the NFT.
@@ -1225,16 +1254,14 @@
pub fn approve(origin, spender: T::AccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {
let sender = ensure_signed(origin)?;
+ let target_collection = Self::get_collection(collection_id)?;
- Self::collection_exists(collection_id)?;
- Self::token_exists(collection_id, item_id, &sender)?;
+ Self::token_exists(&target_collection, item_id, &sender)?;
// Transfer permissions check
- let target_collection = <Collection<T>>::get(collection_id);
-
let bypasses_limits = target_collection.limits.owner_can_transfer &&
Self::is_owner_or_admin_permissions(
- collection_id,
+ &target_collection,
sender.clone(),
);
@@ -1242,7 +1269,7 @@
None
} else if let Some(amount) = Self::owned_amount(
sender.clone(),
- collection_id,
+ &target_collection,
item_id,
) {
Some(amount)
@@ -1251,8 +1278,8 @@
};
if target_collection.access == AccessMode::WhiteList {
- Self::check_white_list(collection_id, &sender)?;
- Self::check_white_list(collection_id, &spender)?;
+ Self::check_white_list(&target_collection, &sender)?;
+ Self::check_white_list(&target_collection, &spender)?;
}
let allowance_exists = <Allowances<T>>::contains_key(collection_id, (item_id, &sender, &spender));
@@ -1292,6 +1319,8 @@
pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResult {
let sender = ensure_signed(origin)?;
+ let target_collection = Self::get_collection(collection_id)?;
+
let mut appoved_transfer = false;
// Check approval
@@ -1302,24 +1331,22 @@
appoved_transfer = true;
}
- let target_collection = <Collection<T>>::get(collection_id);
-
// Limits check
- Self::is_correct_transfer(collection_id, &target_collection, &recipient)?;
+ Self::is_correct_transfer(&target_collection, &recipient)?;
// Transfer permissions check
ensure!(
appoved_transfer ||
(
target_collection.limits.owner_can_transfer &&
- Self::is_owner_or_admin_permissions(collection_id, sender.clone())
+ Self::is_owner_or_admin_permissions(&target_collection, sender.clone())
),
Error::<T>::NoPermission
);
if target_collection.access == AccessMode::WhiteList {
- Self::check_white_list(collection_id, &sender)?;
- Self::check_white_list(collection_id, &recipient)?;
+ Self::check_white_list(&target_collection, &sender)?;
+ Self::check_white_list(&target_collection, &recipient)?;
}
// Reduce approval by transferred amount or remove if remaining approval drops to 0
@@ -1332,9 +1359,9 @@
match target_collection.mode
{
- CollectionMode::NFT => Self::transfer_nft(collection_id, item_id, from, recipient)?,
- CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, value, &from, &recipient)?,
- CollectionMode::ReFungible => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,
+ CollectionMode::NFT => Self::transfer_nft(&target_collection, item_id, from, recipient)?,
+ CollectionMode::Fungible(_) => Self::transfer_fungible(&target_collection, value, &from, &recipient)?,
+ CollectionMode::ReFungible => Self::transfer_refungible(&target_collection, item_id, value, from.clone(), recipient)?,
_ => ()
};
@@ -1378,21 +1405,20 @@
) -> DispatchResult {
let sender = ensure_signed(origin)?;
- Self::collection_exists(collection_id)?;
- Self::token_exists(collection_id, item_id, &sender)?;
+ let target_collection = Self::get_collection(collection_id)?;
+ Self::token_exists(&target_collection, item_id, &sender)?;
ensure!(ChainLimit::get().custom_data_limit >= data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);
// Modify permissions check
- let target_collection = <Collection<T>>::get(collection_id);
- ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) ||
- Self::is_owner_or_admin_permissions(collection_id, sender.clone()),
+ ensure!(Self::is_item_owner(sender.clone(), &target_collection, item_id) ||
+ Self::is_owner_or_admin_permissions(&target_collection, sender.clone()),
Error::<T>::NoPermission);
match target_collection.mode
{
- CollectionMode::NFT => Self::set_nft_variable_data(collection_id, item_id, data)?,
- CollectionMode::ReFungible => Self::set_re_fungible_variable_data(collection_id, item_id, data)?,
+ CollectionMode::NFT => Self::set_nft_variable_data(&target_collection, item_id, data)?,
+ CollectionMode::ReFungible => Self::set_re_fungible_variable_data(&target_collection, item_id, data)?,
CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),
_ => fail!(Error::<T>::UnexpectedCollectionType)
};
@@ -1422,10 +1448,10 @@
version: SchemaVersion
) -> DispatchResult {
let sender = ensure_signed(origin)?;
- Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;
- let mut target_collection = <Collection<T>>::get(collection_id);
+ let mut target_collection = Self::get_collection(collection_id)?;
+ Self::check_owner_or_admin_permissions(&target_collection, sender.clone())?;
target_collection.schema_version = version;
- <Collection<T>>::insert(collection_id, target_collection);
+ Self::save_collection(target_collection);
Ok(())
}
@@ -1450,14 +1476,14 @@
schema: Vec<u8>
) -> DispatchResult {
let sender = ensure_signed(origin)?;
- Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;
+ let mut target_collection = Self::get_collection(collection_id)?;
+ Self::check_owner_or_admin_permissions(&target_collection, sender.clone())?;
// check schema limit
ensure!(schema.len() as u32 <= ChainLimit::get().offchain_schema_limit, "");
- let mut target_collection = <Collection<T>>::get(collection_id);
target_collection.offchain_schema = schema;
- <Collection<T>>::insert(collection_id, target_collection);
+ Self::save_collection(target_collection);
Ok(())
}
@@ -1482,14 +1508,14 @@
schema: Vec<u8>
) -> DispatchResult {
let sender = ensure_signed(origin)?;
- Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;
+ let mut target_collection = Self::get_collection(collection_id)?;
+ Self::check_owner_or_admin_permissions(&target_collection, sender.clone())?;
// check schema limit
ensure!(schema.len() as u32 <= ChainLimit::get().const_on_chain_schema_limit, "");
- let mut target_collection = <Collection<T>>::get(collection_id);
target_collection.const_on_chain_schema = schema;
- <Collection<T>>::insert(collection_id, target_collection);
+ Self::save_collection(target_collection);
Ok(())
}
@@ -1514,14 +1540,14 @@
schema: Vec<u8>
) -> DispatchResult {
let sender = ensure_signed(origin)?;
- Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;
+ let mut target_collection = Self::get_collection(collection_id)?;
+ Self::check_owner_or_admin_permissions(&target_collection, sender.clone())?;
// check schema limit
ensure!(schema.len() as u32 <= ChainLimit::get().variable_on_chain_schema_limit, "");
- let mut target_collection = <Collection<T>>::get(collection_id);
target_collection.variable_on_chain_schema = schema;
- <Collection<T>>::insert(collection_id, target_collection);
+ Self::save_collection(target_collection);
Ok(())
}
@@ -1694,12 +1720,12 @@
pub fn set_collection_limits(
origin,
collection_id: u32,
- new_limits: CollectionLimits,
+ new_limits: CollectionLimits<T::BlockNumber>,
) -> DispatchResult {
let sender = ensure_signed(origin)?;
- Self::check_owner_permissions(collection_id, sender.clone())?;
- let mut target_collection = <Collection<T>>::get(collection_id);
- let old_limits = target_collection.limits;
+ let mut target_collection = Self::get_collection(collection_id)?;
+ Self::check_owner_permissions(&target_collection, sender.clone())?;
+ let old_limits = &target_collection.limits;
let chain_limits = ChainLimit::get();
// collection bounds
@@ -1719,7 +1745,7 @@
);
target_collection.limits = new_limits;
- <Collection<T>>::insert(collection_id, target_collection);
+ Self::save_collection(target_collection);
Ok(())
}
@@ -1728,38 +1754,36 @@
impl<T: Config> Module<T> {
- pub fn transfer_internal(sender: T::AccountId, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {
-
- let target_collection = <Collection<T>>::get(collection_id);
-
+ pub fn transfer_internal(sender: T::AccountId, recipient: T::AccountId, target_collection: &CollectionHandle<T>, item_id: TokenId, value: u128) -> DispatchResult {
// Limits check
- Self::is_correct_transfer(collection_id, &target_collection, &recipient)?;
+ Self::is_correct_transfer(target_collection, &recipient)?;
// Transfer permissions check
- ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) ||
- Self::is_owner_or_admin_permissions(collection_id, sender.clone()),
+ ensure!(Self::is_item_owner(sender.clone(), target_collection, item_id) ||
+ Self::is_owner_or_admin_permissions(target_collection, sender.clone()),
Error::<T>::NoPermission);
if target_collection.access == AccessMode::WhiteList {
- Self::check_white_list(collection_id, &sender)?;
- Self::check_white_list(collection_id, &recipient)?;
+ Self::check_white_list(target_collection, &sender)?;
+ Self::check_white_list(target_collection, &recipient)?;
}
match target_collection.mode
{
- CollectionMode::NFT => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient.clone())?,
- CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, value, &sender, &recipient)?,
- CollectionMode::ReFungible => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient.clone())?,
+ CollectionMode::NFT => Self::transfer_nft(target_collection, item_id, sender.clone(), recipient.clone())?,
+ CollectionMode::Fungible(_) => Self::transfer_fungible(target_collection, value, &sender, &recipient)?,
+ CollectionMode::ReFungible => Self::transfer_refungible(target_collection, item_id, value, sender.clone(), recipient.clone())?,
_ => ()
};
- Self::deposit_event(RawEvent::Transfer(collection_id, item_id, sender, recipient, value));
+ Self::deposit_event(RawEvent::Transfer(target_collection.id, item_id, sender, recipient, value));
Ok(())
}
- fn is_correct_transfer(collection_id: CollectionId, collection: &CollectionType<T::AccountId>, recipient: &T::AccountId) -> DispatchResult {
+ fn is_correct_transfer(collection: &CollectionHandle<T>, recipient: &T::AccountId) -> DispatchResult {
+ let collection_id = collection.id;
// check token limit and account token limit
let account_items: u32 = <AddressTokens<T>>::get(collection_id, recipient).len() as u32;
@@ -1768,7 +1792,8 @@
Ok(())
}
- fn can_create_items_in_collection(collection_id: CollectionId, collection: &CollectionType<T::AccountId>, sender: &T::AccountId, owner: &T::AccountId, amount: u32) -> DispatchResult {
+ fn can_create_items_in_collection(collection: &CollectionHandle<T>, sender: &T::AccountId, owner: &T::AccountId, amount: u32) -> DispatchResult {
+ let collection_id = collection.id;
// check token limit and account token limit
let total_items: u32 = ItemListIndex::get(collection_id)
@@ -1780,16 +1805,16 @@
ensure!(collection.limits.token_limit >= total_items, Error::<T>::CollectionTokenLimitExceeded);
ensure!(collection.limits.account_token_ownership_limit >= account_items, Error::<T>::AccountTokenLimitExceeded);
- if !Self::is_owner_or_admin_permissions(collection_id, sender.clone()) {
+ if !Self::is_owner_or_admin_permissions(collection, sender.clone()) {
ensure!(collection.mint_mode == true, Error::<T>::PublicMintingNotAllowed);
- Self::check_white_list(collection_id, owner)?;
- Self::check_white_list(collection_id, sender)?;
+ Self::check_white_list(collection, owner)?;
+ Self::check_white_list(collection, sender)?;
}
Ok(())
}
- fn validate_create_item_args(target_collection: &CollectionType<T::AccountId>, data: &CreateItemData) -> DispatchResult {
+ fn validate_create_item_args(target_collection: &CollectionHandle<T>, data: &CreateItemData) -> DispatchResult {
match target_collection.mode
{
CollectionMode::NFT => {
@@ -1827,7 +1852,9 @@
Ok(())
}
- fn create_item_no_validation(collection_id: CollectionId, owner: T::AccountId, data: CreateItemData) -> DispatchResult {
+ fn create_item_no_validation(collection: &CollectionHandle<T>, owner: T::AccountId, data: CreateItemData) -> DispatchResult {
+ let collection_id = collection.id;
+
match data
{
CreateItemData::NFT(data) => {
@@ -1837,10 +1864,10 @@
variable_data: data.variable_data
};
- Self::add_nft_item(collection_id, item)?;
+ Self::add_nft_item(collection, item)?;
},
CreateItemData::Fungible(data) => {
- Self::add_fungible_item(collection_id, &owner, data.value)?;
+ Self::add_fungible_item(collection, &owner, data.value)?;
},
CreateItemData::ReFungible(data) => {
let mut owner_list = Vec::new();
@@ -1852,14 +1879,15 @@
variable_data: data.variable_data
};
- Self::add_refungible_item(collection_id, item)?;
+ Self::add_refungible_item(collection, item)?;
}
};
Ok(())
}
- fn add_fungible_item(collection_id: CollectionId, owner: &T::AccountId, value: u128) -> DispatchResult {
+ fn add_fungible_item(collection: &CollectionHandle<T>, owner: &T::AccountId, value: u128) -> DispatchResult {
+ let collection_id = collection.id;
// Does new owner already have an account?
let mut balance: u128 = 0;
@@ -1883,7 +1911,9 @@
Ok(())
}
- fn add_refungible_item(collection_id: CollectionId, item: ReFungibleItemType<T::AccountId>) -> DispatchResult {
+ fn add_refungible_item(collection: &CollectionHandle<T>, item: ReFungibleItemType<T::AccountId>) -> DispatchResult {
+ let collection_id = collection.id;
+
let current_index = <ItemListIndex>::get(collection_id)
.checked_add(1)
.ok_or(Error::<T>::NumOverflow)?;
@@ -1913,7 +1943,9 @@
Ok(())
}
- fn add_nft_item(collection_id: CollectionId, item: NftItemType<T::AccountId>) -> DispatchResult {
+ fn add_nft_item(collection: &CollectionHandle<T>, item: NftItemType<T::AccountId>) -> DispatchResult {
+ let collection_id = collection.id;
+
let current_index = <ItemListIndex>::get(collection_id)
.checked_add(1)
.ok_or(Error::<T>::NumOverflow)?;
@@ -1935,10 +1967,12 @@
}
fn burn_refungible_item(
- collection_id: CollectionId,
+ collection: &CollectionHandle<T>,
item_id: TokenId,
owner: &T::AccountId,
) -> DispatchResult {
+ let collection_id = collection.id;
+
ensure!(
<ReFungibleItemList<T>>::contains_key(collection_id, item_id),
Error::<T>::TokenNotFound
@@ -1969,6 +2003,7 @@
// Burn the token completely if this was the last (only) owner
if owner_count == 0 {
<ReFungibleItemList<T>>::remove(collection_id, item_id);
+ <VariableMetaDataBasket<T>>::remove(collection_id, item_id);
}
else {
<ReFungibleItemList<T>>::insert(collection_id, item_id, token);
@@ -1977,7 +2012,9 @@
Ok(())
}
- fn burn_nft_item(collection_id: CollectionId, item_id: TokenId) -> DispatchResult {
+ fn burn_nft_item(collection: &CollectionHandle<T>, item_id: TokenId) -> DispatchResult {
+ let collection_id = collection.id;
+
ensure!(
<NftItemList<T>>::contains_key(collection_id, item_id),
Error::<T>::TokenNotFound
@@ -1991,11 +2028,14 @@
.ok_or(Error::<T>::NumOverflow)?;
<Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);
<NftItemList<T>>::remove(collection_id, item_id);
+ <VariableMetaDataBasket<T>>::remove(collection_id, item_id);
Ok(())
}
- fn burn_fungible_item(owner: &T::AccountId, collection_id: CollectionId, value: u128) -> DispatchResult {
+ fn burn_fungible_item(owner: &T::AccountId, collection: &CollectionHandle<T>, value: u128) -> DispatchResult {
+ let collection_id = collection.id;
+
ensure!(
<FungibleItemList<T>>::contains_key(collection_id, owner),
Error::<T>::TokenNotFound
@@ -2020,18 +2060,20 @@
Ok(())
}
- fn collection_exists(collection_id: CollectionId) -> DispatchResult {
- ensure!(
- <Collection<T>>::contains_key(collection_id),
- Error::<T>::CollectionNotFound
- );
- Ok(())
+ pub fn get_collection(collection_id: CollectionId) -> Result<CollectionHandle<T>, sp_runtime::DispatchError> {
+ Ok(<CollectionById<T>>::get(collection_id)
+ .map(|collection| CollectionHandle {
+ id: collection_id,
+ collection
+ })
+ .ok_or(Error::<T>::CollectionNotFound)?)
}
- fn check_owner_permissions(collection_id: CollectionId, subject: T::AccountId) -> DispatchResult {
- Self::collection_exists(collection_id)?;
+ fn save_collection(collection: CollectionHandle<T>) {
+ <CollectionById<T>>::insert(collection.id, collection.collection);
+ }
- let target_collection = <Collection<T>>::get(collection_id);
+ fn check_owner_permissions(target_collection: &CollectionHandle<T>, subject: T::AccountId) -> DispatchResult {
ensure!(
subject == target_collection.owner,
Error::<T>::NoPermission
@@ -2040,13 +2082,12 @@
Ok(())
}
- fn is_owner_or_admin_permissions(collection_id: CollectionId, subject: T::AccountId) -> bool {
- let target_collection = <Collection<T>>::get(collection_id);
- let mut result: bool = subject == target_collection.owner;
- let exists = <AdminList<T>>::contains_key(collection_id);
+ fn is_owner_or_admin_permissions(collection: &CollectionHandle<T>, subject: T::AccountId) -> bool {
+ let mut result: bool = subject == collection.owner;
+ let exists = <AdminList<T>>::contains_key(collection.id);
if !result & exists {
- if <AdminList<T>>::get(collection_id).contains(&subject) {
+ if <AdminList<T>>::get(collection.id).contains(&subject) {
result = true
}
}
@@ -2055,11 +2096,10 @@
}
fn check_owner_or_admin_permissions(
- collection_id: CollectionId,
+ collection: &CollectionHandle<T>,
subject: T::AccountId,
) -> DispatchResult {
- Self::collection_exists(collection_id)?;
- let result = Self::is_owner_or_admin_permissions(collection_id, subject.clone());
+ let result = Self::is_owner_or_admin_permissions(collection, subject.clone());
ensure!(
result,
@@ -2070,10 +2110,10 @@
fn owned_amount(
subject: T::AccountId,
- collection_id: CollectionId,
+ target_collection: &CollectionHandle<T>,
item_id: TokenId,
) -> Option<u128> {
- let target_collection = <Collection<T>>::get(collection_id);
+ let collection_id = target_collection.id;
match target_collection.mode {
CollectionMode::NFT => {
@@ -2098,8 +2138,8 @@
}
}
- fn is_item_owner(subject: T::AccountId, collection_id: CollectionId, item_id: TokenId) -> bool {
- let target_collection = <Collection<T>>::get(collection_id);
+ fn is_item_owner(subject: T::AccountId, target_collection: &CollectionHandle<T>, item_id: TokenId) -> bool {
+ let collection_id = target_collection.id;
match target_collection.mode {
CollectionMode::NFT => {
@@ -2118,7 +2158,9 @@
}
}
- fn check_white_list(collection_id: CollectionId, address: &T::AccountId) -> DispatchResult {
+ fn check_white_list(collection: &CollectionHandle<T>, address: &T::AccountId) -> DispatchResult {
+ let collection_id = collection.id;
+
let mes = Error::<T>::AddresNotInWhiteList;
ensure!(<WhiteList<T>>::contains_key(collection_id, address), mes);
@@ -2128,11 +2170,11 @@
/// Check if token exists. In case of Fungible, check if there is an entry for
/// the owner in fungible balances double map
fn token_exists(
- collection_id: CollectionId,
+ target_collection: &CollectionHandle<T>,
item_id: TokenId,
owner: &T::AccountId
) -> DispatchResult {
- let target_collection = <Collection<T>>::get(collection_id);
+ let collection_id = target_collection.id;
let exists = match target_collection.mode
{
CollectionMode::NFT => <NftItemList<T>>::contains_key(collection_id, item_id),
@@ -2146,18 +2188,19 @@
}
fn transfer_fungible(
- collection_id: CollectionId,
+ collection: &CollectionHandle<T>,
value: u128,
owner: &T::AccountId,
recipient: &T::AccountId,
) -> DispatchResult {
- Self::token_exists(collection_id, 0, owner)?;
+ let collection_id = collection.id;
+ Self::token_exists(&collection, 0, owner)?;
let mut balance = <FungibleItemList<T>>::get(collection_id, owner);
ensure!(balance.value >= value, Error::<T>::TokenValueTooLow);
// Send balance to recipient (updates balanceOf of recipient)
- Self::add_fungible_item(collection_id, recipient, value)?;
+ Self::add_fungible_item(collection, recipient, value)?;
// update balanceOf of sender
<Balance<T>>::insert(collection_id, (*owner).clone(), balance.value - value);
@@ -2175,13 +2218,14 @@
}
fn transfer_refungible(
- collection_id: CollectionId,
+ collection: &CollectionHandle<T>,
item_id: TokenId,
value: u128,
owner: T::AccountId,
new_owner: T::AccountId,
) -> DispatchResult {
- Self::token_exists(collection_id, item_id, &owner)?;
+ let collection_id = collection.id;
+ Self::token_exists(collection, item_id, &owner)?;
let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);
let item = full_item
@@ -2257,12 +2301,13 @@
}
fn transfer_nft(
- collection_id: CollectionId,
+ collection: &CollectionHandle<T>,
item_id: TokenId,
sender: T::AccountId,
new_owner: T::AccountId,
) -> DispatchResult {
- Self::token_exists(collection_id, item_id, &sender)?;
+ let collection_id = collection.id;
+ Self::token_exists(&collection, item_id, &sender)?;
let mut item = <NftItemList<T>>::get(collection_id, item_id);
@@ -2294,10 +2339,11 @@
}
fn set_re_fungible_variable_data(
- collection_id: CollectionId,
+ collection: &CollectionHandle<T>,
item_id: TokenId,
data: Vec<u8>
) -> DispatchResult {
+ let collection_id = collection.id;
let mut item = <ReFungibleItemList<T>>::get(collection_id, item_id);
item.variable_data = data;
@@ -2308,10 +2354,11 @@
}
fn set_nft_variable_data(
- collection_id: CollectionId,
+ collection: &CollectionHandle<T>,
item_id: TokenId,
data: Vec<u8>
) -> DispatchResult {
+ let collection_id = collection.id;
let mut item = <NftItemList<T>>::get(collection_id, item_id);
item.variable_data = data;
@@ -2321,7 +2368,7 @@
Ok(())
}
- fn init_collection(item: &CollectionType<T::AccountId>) {
+ fn init_collection(item: &Collection<T>) {
// check params
assert!(
item.decimal_points <= MAX_DECIMAL_POINTS,
@@ -2401,7 +2448,6 @@
}
fn add_token_index(collection_id: CollectionId, item_index: TokenId, owner: &T::AccountId) -> DispatchResult {
-
// add to account limit
if <AccountItemCount<T>>::contains_key(owner) {
@@ -2569,8 +2615,9 @@
// Determine who is paying transaction fee based on ecnomic model
// Parse call to extract collection ID and access collection sponsor
- let mut sponsor: T::AccountId = match IsSubType::<Call<T>>::is_sub_type(call) {
+ let mut sponsor: Option<T::AccountId> = (|| match IsSubType::<Call<T>>::is_sub_type(call) {
Some(Call::create_item(collection_id, _owner, _properties)) => {
+ let collection = <CollectionById<T>>::get(collection_id)?;
// sponsor timeout
let block_number = <system::Module<T>>::block_number() as T::BlockNumber;
@@ -2583,12 +2630,10 @@
let last_tx_block = <CreateItemBasket<T>>::get((collection_id, &who));
let limit_time = last_tx_block + limit.into();
if block_number <= limit_time {
- sponsored = false;
+ return None;
}
}
- if sponsored {
- <CreateItemBasket<T>>::insert((collection_id, who.clone()), block_number);
- }
+ <CreateItemBasket<T>>::insert((collection_id, who.clone()), block_number);
// check free create limit
if (collection.limits.sponsored_data_size >= (_properties.len() as u32)) &&
@@ -2596,18 +2641,18 @@
{
collection.sponsorship.sponsor()
.cloned()
- .unwrap_or_default()
} else {
- T::AccountId::default()
+ None
}
}
Some(Call::transfer(_new_owner, collection_id, item_id, _value)) => {
+ let collection = <CollectionById<T>>::get(collection_id)?;
let mut sponsor_transfer = false;
- if <Collection<T>>::get(collection_id).sponsorship.confirmed() {
+ if collection.sponsorship.confirmed() {
- let collection_limits = <Collection<T>>::get(collection_id).limits;
- let collection_mode = <Collection<T>>::get(collection_id).mode;
+ let collection_limits = collection.limits;
+ let collection_mode = collection.mode;
// sponsor timeout
let block_number = <system::Module<T>>::block_number() as T::BlockNumber;
@@ -2689,19 +2734,68 @@
}
if !sponsor_transfer {
- T::AccountId::default()
+ None
} else {
- <Collection<T>>::get(collection_id).sponsorship.sponsor()
+ collection.sponsorship.sponsor()
.cloned()
- .unwrap_or_default()
}
}
- _ => T::AccountId::default(),
- };
+ Some(Call::set_variable_meta_data(collection_id, item_id, data)) => {
+ let mut sponsor_metadata_changes = false;
+
+ let collection = <CollectionById<T>>::get(collection_id)?;
+
+ if
+ collection.sponsor_confirmed &&
+ // Can't sponsor fungible collection, this tx will be rejected
+ // as invalid
+ !matches!(collection.mode, CollectionMode::Fungible(_)) &&
+ data.len() <= collection.limits.sponsored_data_size as usize
+ {
+ if let Some(rate_limit) = collection.limits.sponsored_data_rate_limit {
+ let block_number = <system::Module<T>>::block_number() as T::BlockNumber;
+
+ if <VariableMetaDataBasket<T>>::get(collection_id, item_id)
+ .map(|last_block| block_number - last_block > rate_limit)
+ .unwrap_or(true)
+ {
+ sponsor_metadata_changes = true;
+ <VariableMetaDataBasket<T>>::insert(collection_id, item_id, block_number);
+ }
+ }
+ }
+
+ if !sponsor_metadata_changes {
+ None
+ } else {
+ Some(collection.sponsor)
+ }
+ }
+
+ _ => None,
+ })();
+
+ match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {
+ Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {
+ let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());
+
+ let owned_contract = <ContractOwner<T>>::contains_key(called_contract.clone())
+ && <ContractOwner<T>>::get(called_contract.clone()) == *who;
+ let white_list_enabled = <ContractWhiteListEnabled<T>>::contains_key(called_contract.clone()) && <ContractWhiteListEnabled<T>>::get(called_contract.clone());
+
+ if !owned_contract && white_list_enabled {
+ if !<ContractWhiteList<T>>::contains_key(called_contract.clone(), who) {
+ return Err(InvalidTransaction::Call.into());
+ }
+ }
+ },
+ _ => {},
+ }
+
// Sponsor smart contracts
- sponsor = match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {
+ sponsor = sponsor.or_else(|| match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {
// On instantiation: set the contract owner
Some(pallet_contracts::Call::instantiate(_endowment, _gas_limit, code_hash, _data, salt)) => {
@@ -2713,7 +2807,7 @@
);
<ContractOwner<T>>::insert(new_contract_address.clone(), who.clone());
- T::AccountId::default()
+ None
},
// On instantiation with code: set the contract owner
@@ -2727,23 +2821,13 @@
<ContractOwner<T>>::insert(new_contract_address.clone(), who.clone());
- T::AccountId::default()
+ None
}
// When the contract is called, check if the sponsoring is enabled and pay fees from contract endowment if it is
Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {
let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());
-
- let owned_contract = <ContractOwner<T>>::contains_key(called_contract.clone())
- && <ContractOwner<T>>::get(called_contract.clone()) == *who;
- let white_list_enabled = <ContractWhiteListEnabled<T>>::contains_key(called_contract.clone()) && <ContractWhiteListEnabled<T>>::get(called_contract.clone());
-
- if !owned_contract && white_list_enabled {
- if !<ContractWhiteList<T>>::contains_key(called_contract.clone(), who) {
- return Err(InvalidTransaction::Call.into());
- }
- }
let mut sponsor_transfer = false;
if <ContractSponsoringRateLimit<T>>::contains_key(called_contract.clone()) {
@@ -2760,26 +2844,21 @@
sponsor_transfer = false;
}
-
- let mut sp = T::AccountId::default();
if sponsor_transfer {
if <ContractSelfSponsoring<T>>::contains_key(called_contract.clone()) {
if <ContractSelfSponsoring<T>>::get(called_contract.clone()) {
- sp = called_contract;
+ return Some(called_contract);
}
}
}
- sp
+ None
},
- _ => sponsor,
- };
+ _ => None,
+ });
- let mut who_pays_fee: T::AccountId = sponsor.clone();
- if sponsor == T::AccountId::default() {
- who_pays_fee = who.clone();
- }
+ let who_pays_fee = sponsor.unwrap_or_else(|| who.clone());
<<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::withdraw_fee(&who_pays_fee, call, info, fee, tip)
.map(|i| (fee, i))
pallets/nft/src/tests.rsdiffbeforeafterboth--- a/pallets/nft/src/tests.rs
+++ b/pallets/nft/src/tests.rs
@@ -55,11 +55,11 @@
let saved_col_name: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();
let saved_description: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();
let saved_prefix: Vec<u8> = b"token_prefix1\0".to_vec();
- assert_eq!(TemplateModule::collection(id).owner, owner);
- assert_eq!(TemplateModule::collection(id).name, saved_col_name);
- assert_eq!(TemplateModule::collection(id).mode, *mode);
- assert_eq!(TemplateModule::collection(id).description, saved_description);
- assert_eq!(TemplateModule::collection(id).token_prefix, saved_prefix);
+ assert_eq!(TemplateModule::collection_id(id).unwrap().owner, owner);
+ assert_eq!(TemplateModule::collection_id(id).unwrap().name, saved_col_name);
+ assert_eq!(TemplateModule::collection_id(id).unwrap().mode, *mode);
+ assert_eq!(TemplateModule::collection_id(id).unwrap().description, saved_description);
+ assert_eq!(TemplateModule::collection_id(id).unwrap().token_prefix, saved_prefix);
id
}
@@ -89,7 +89,7 @@
let collection_id = create_test_collection(&CollectionMode::NFT, 1);
assert_ok!(TemplateModule::set_schema_version(origin1, collection_id, SchemaVersion::Unique));
- assert_eq!(TemplateModule::collection(collection_id).schema_version, SchemaVersion::Unique);
+ assert_eq!(TemplateModule::collection_id(collection_id).unwrap().schema_version, SchemaVersion::Unique);
});
}
@@ -622,7 +622,7 @@
collection_id,
2
));
- assert_eq!(TemplateModule::collection(collection_id).owner, 2);
+ assert_eq!(TemplateModule::collection_id(collection_id).unwrap().owner, 2);
});
}
@@ -1841,8 +1841,8 @@
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::set_const_on_chain_schema(origin1, collection_id, b"test const on chain schema".to_vec()));
- assert_eq!(TemplateModule::collection(collection_id).const_on_chain_schema, b"test const on chain schema".to_vec());
- assert_eq!(TemplateModule::collection(collection_id).variable_on_chain_schema, b"".to_vec());
+ assert_eq!(TemplateModule::collection_id(collection_id).unwrap().const_on_chain_schema, b"test const on chain schema".to_vec());
+ assert_eq!(TemplateModule::collection_id(collection_id).unwrap().variable_on_chain_schema, b"".to_vec());
});
}
@@ -1856,8 +1856,8 @@
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::set_variable_on_chain_schema(origin1, collection_id, b"test variable on chain schema".to_vec()));
- assert_eq!(TemplateModule::collection(collection_id).const_on_chain_schema, b"".to_vec());
- assert_eq!(TemplateModule::collection(collection_id).variable_on_chain_schema, b"test variable on chain schema".to_vec());
+ assert_eq!(TemplateModule::collection_id(collection_id).unwrap().const_on_chain_schema, b"".to_vec());
+ assert_eq!(TemplateModule::collection_id(collection_id).unwrap().variable_on_chain_schema, b"test variable on chain schema".to_vec());
});
}
runtime/src/chain_extension.rsdiffbeforeafterboth--- a/runtime/src/chain_extension.rs
+++ b/runtime/src/chain_extension.rs
@@ -60,7 +60,9 @@
}
let recipient = AccountId32::from(bytes_rec);
- match pallet_nft::Module::<Runtime>::transfer_internal(sender, recipient, input.collection_id, input.token_id, input.amount) {
+ let collection = pallet_nft::Module::<Runtime>::get_collection(input.collection_id)?;
+
+ match pallet_nft::Module::<Runtime>::transfer_internal(sender, recipient, &collection, input.token_id, input.amount) {
Ok(_) => Ok(RetVal::Converging(func_id)),
_ => Err(DispatchError::Other("Transfer error"))
}
runtime/src/nft_weights.rsdiffbeforeafterboth--- a/runtime/src/nft_weights.rs
+++ b/runtime/src/nft_weights.rs
@@ -133,6 +133,11 @@
.saturating_add(DbWeight::get().reads(0 as Weight))
.saturating_add(DbWeight::get().writes(2 as Weight))
}
+ fn set_variable_meta_data_sponsoring_rate_limit() -> Weight {
+ (3_500_000 as Weight)
+ .saturating_add(DbWeight::get().reads(1 as Weight))
+ .saturating_add(DbWeight::get().writes(2 as Weight))
+ }
fn toggle_contract_white_list() -> Weight {
(3_000_000 as Weight)
.saturating_add(DbWeight::get().reads(0 as Weight))
runtime_types.jsondiffbeforeafterboth--- a/runtime_types.json
+++ b/runtime_types.json
@@ -38,7 +38,7 @@
"Confirmed": "AccountId"
}
},
- "CollectionType": {
+ "Collection": {
"Owner": "AccountId",
"Mode": "CollectionMode",
"Access": "AccessMode",
@@ -99,7 +99,8 @@
},
"CollectionLimits": {
"AccountTokenOwnershipLimit": "u32",
- "SponsoredMintSize": "u32",
+ "SponsoredDataSize": "u32",
+ "SponsoredDataRateLimit": "Option<BlockNumber>",
"TokenLimit": "u32",
"SponsorTimeout": "u32",
"OwnerCanTransfer": "bool",
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -46,7 +46,8 @@
"testEnableContractSponsoring": "mocha --timeout 9999999 -r ts-node/register ./**/enableContractSponsoring.test.ts",
"testSetContractSponsoringRateLimit": "mocha --timeout 9999999 -r ts-node/register ./**/setContractSponsoringRateLimit.test.ts",
"testSetOffchainSchema": "mocha --timeout 9999999 -r ts-node/register ./**/setOffchainSchema.test.ts",
- "testOverflow": "mocha --timeout 9999999 -r ts-node/register ./**/overflow.test.ts"
+ "testOverflow": "mocha --timeout 9999999 -r ts-node/register ./**/overflow.test.ts",
+ "testSetVariableMetadataSponsoringRateLimit": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetadataSponsoringRateLimit.test.ts"
},
"author": "",
"license": "SEE LICENSE IN ../LICENSE",
tests/src/addCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/addCollectionAdmin.test.ts
+++ b/tests/src/addCollectionAdmin.test.ts
@@ -1,135 +1,135 @@
-//
-// This file is subject to the terms and conditions defined in
-// file 'LICENSE', which is part of this source code package.
-//
-
-import { ApiPromise } from '@polkadot/api';
-import BN from 'bn.js';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import privateKey from './substrate/privateKey';
-import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';
-import {createCollectionExpectSuccess, destroyCollectionExpectSuccess} from './util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-describe('Integration Test addCollectionAdmin(collection_id, new_admin_id):', () => {
- it('Add collection admin.', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- const alice = privateKey('//Alice');
- const bob = privateKey('//Bob');
-
- const collection: any = (await api.query.nft.collection(collectionId));
- expect(collection.Owner.toString()).to.be.eq(alice.address);
-
- const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, bob.address);
- await submitTransactionAsync(alice, changeAdminTx);
-
- const adminListAfterAddAdmin: any = (await api.query.nft.adminList(collectionId));
- expect(adminListAfterAddAdmin).to.be.contains(bob.address);
- });
- });
-
- it('Add admin using added collection admin.', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- const Alice = privateKey('//Alice');
- const Bob = privateKey('//Bob');
- const Charlie = privateKey('//CHARLIE');
-
- const collection: any = (await api.query.nft.collection(collectionId));
- expect(collection.Owner.toString()).to.be.eq(Alice.address);
-
- const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, Bob.address);
- await submitTransactionAsync(Alice, changeAdminTx);
-
- const adminListAfterAddAdmin: any = (await api.query.nft.adminList(collectionId));
- expect(adminListAfterAddAdmin).to.be.contains(Bob.address);
-
- const changeAdminTxCharlie = api.tx.nft.addCollectionAdmin(collectionId, Charlie.address);
- await submitTransactionAsync(Bob, changeAdminTxCharlie);
- const adminListAfterAddNewAdmin: any = (await api.query.nft.adminList(collectionId));
- expect(adminListAfterAddNewAdmin).to.be.contains(Bob.address);
- expect(adminListAfterAddNewAdmin).to.be.contains(Charlie.address);
- });
- });
-});
-
-describe('Negative Integration Test addCollectionAdmin(collection_id, new_admin_id):', () => {
- it("Not owner can't add collection admin.", async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- const alice = privateKey('//Alice');
- const nonOwner = privateKey('//Bob_stash');
-
- const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, alice.address);
- await expect(submitTransactionExpectFailAsync(nonOwner, changeAdminTx)).to.be.rejected;
-
- const adminListAfterAddAdmin: any = (await api.query.nft.adminList(collectionId));
- expect(adminListAfterAddAdmin).not.to.be.contains(alice.address);
-
- // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
- await createCollectionExpectSuccess();
- });
- });
- it("Can't add collection admin of not existing collection.", async () => {
- await usingApi(async (api) => {
- // tslint:disable-next-line: no-bitwise
- const collectionId = (1 << 32) - 1;
- const alice = privateKey('//Alice');
- const bob = privateKey('//Bob');
-
- const changeOwnerTx = api.tx.nft.addCollectionAdmin(collectionId, bob.address);
- await expect(submitTransactionExpectFailAsync(alice, changeOwnerTx)).to.be.rejected;
-
- // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
- await createCollectionExpectSuccess();
- });
- });
-
- it("Can't add an admin to a destroyed collection.", async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- const Alice = privateKey('//Alice');
- const Bob = privateKey('//Bob');
- await destroyCollectionExpectSuccess(collectionId);
- const changeOwnerTx = api.tx.nft.addCollectionAdmin(collectionId, Bob.address);
- await expect(submitTransactionExpectFailAsync(Alice, changeOwnerTx)).to.be.rejected;
-
- // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
- await createCollectionExpectSuccess();
- });
- });
-
- it('Add an admin to a collection that has reached the maximum number of admins limit', async () => {
- await usingApi(async (api: ApiPromise) => {
- const Alice = privateKey('//Alice');
- const accounts = [
- 'GsvVmjr1CBHwQHw84pPHMDxgNY3iBLz6Qn7qS3CH8qPhrHz',
- 'FoQJpPyadYccjavVdTWxpxU7rUEaYhfLCPwXgkfD6Zat9QP',
- 'JKspFU6ohf1Grg3Phdzj2pSgWvsYWzSfKghhfzMbdhNBWs5',
- 'Fr4NzY1udSFFLzb2R3qxVQkwz9cZraWkyfH4h3mVVk7BK7P',
- 'DfnTB4z7eUvYRqcGtTpFsLC69o6tvBSC1pEv8vWPZFtCkaK',
- 'HnMAUz7r2G8G3hB27SYNyit5aJmh2a5P4eMdDtACtMFDbam',
- 'DE14BzQ1bDXWPKeLoAqdLAm1GpyAWaWF1knF74cEZeomTBM',
- ];
- const collectionId = await createCollectionExpectSuccess();
-
- const chainLimit = await api.query.nft.chainLimit() as unknown as { CollectionAdminsLimit: BN };
- const chainAdminLimit = chainLimit.CollectionAdminsLimit.toNumber();
- expect(chainAdminLimit).to.be.equal(5);
-
- for (let i = 0; i < chainAdminLimit; i++) {
- const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, accounts[i]);
- await submitTransactionAsync(Alice, changeAdminTx);
- const adminListAfterAddAdmin: any = (await api.query.nft.adminList(collectionId));
- expect(adminListAfterAddAdmin).to.be.contains(accounts[i]);
- }
-
- const tx = api.tx.nft.addCollectionAdmin(collectionId, accounts[chainAdminLimit]);
- await expect(submitTransactionExpectFailAsync(Alice, tx)).to.be.rejected;
- });
- });
-});
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+import { ApiPromise } from '@polkadot/api';
+import BN from 'bn.js';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from './substrate/privateKey';
+import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';
+import {createCollectionExpectSuccess, destroyCollectionExpectSuccess} from './util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+describe('Integration Test addCollectionAdmin(collection_id, new_admin_id):', () => {
+ it('Add collection admin.', async () => {
+ await usingApi(async (api) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+
+ const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
+ expect(collection.Owner.toString()).to.be.eq(alice.address);
+
+ const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, bob.address);
+ await submitTransactionAsync(alice, changeAdminTx);
+
+ const adminListAfterAddAdmin: any = (await api.query.nft.adminList(collectionId));
+ expect(adminListAfterAddAdmin).to.be.contains(bob.address);
+ });
+ });
+
+ it('Add admin using added collection admin.', async () => {
+ await usingApi(async (api) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const Alice = privateKey('//Alice');
+ const Bob = privateKey('//Bob');
+ const Charlie = privateKey('//CHARLIE');
+
+ const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
+ expect(collection.Owner.toString()).to.be.eq(Alice.address);
+
+ const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, Bob.address);
+ await submitTransactionAsync(Alice, changeAdminTx);
+
+ const adminListAfterAddAdmin: any = (await api.query.nft.adminList(collectionId));
+ expect(adminListAfterAddAdmin).to.be.contains(Bob.address);
+
+ const changeAdminTxCharlie = api.tx.nft.addCollectionAdmin(collectionId, Charlie.address);
+ await submitTransactionAsync(Bob, changeAdminTxCharlie);
+ const adminListAfterAddNewAdmin: any = (await api.query.nft.adminList(collectionId));
+ expect(adminListAfterAddNewAdmin).to.be.contains(Bob.address);
+ expect(adminListAfterAddNewAdmin).to.be.contains(Charlie.address);
+ });
+ });
+});
+
+describe('Negative Integration Test addCollectionAdmin(collection_id, new_admin_id):', () => {
+ it("Not owner can't add collection admin.", async () => {
+ await usingApi(async (api) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const alice = privateKey('//Alice');
+ const nonOwner = privateKey('//Bob_stash');
+
+ const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, alice.address);
+ await expect(submitTransactionExpectFailAsync(nonOwner, changeAdminTx)).to.be.rejected;
+
+ const adminListAfterAddAdmin: any = (await api.query.nft.adminList(collectionId));
+ expect(adminListAfterAddAdmin).not.to.be.contains(alice.address);
+
+ // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
+ await createCollectionExpectSuccess();
+ });
+ });
+ it("Can't add collection admin of not existing collection.", async () => {
+ await usingApi(async (api) => {
+ // tslint:disable-next-line: no-bitwise
+ const collectionId = (1 << 32) - 1;
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+
+ const changeOwnerTx = api.tx.nft.addCollectionAdmin(collectionId, bob.address);
+ await expect(submitTransactionExpectFailAsync(alice, changeOwnerTx)).to.be.rejected;
+
+ // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
+ await createCollectionExpectSuccess();
+ });
+ });
+
+ it("Can't add an admin to a destroyed collection.", async () => {
+ await usingApi(async (api) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const Alice = privateKey('//Alice');
+ const Bob = privateKey('//Bob');
+ await destroyCollectionExpectSuccess(collectionId);
+ const changeOwnerTx = api.tx.nft.addCollectionAdmin(collectionId, Bob.address);
+ await expect(submitTransactionExpectFailAsync(Alice, changeOwnerTx)).to.be.rejected;
+
+ // Verifying that nothing bad happened (network is live, new collections can be created, etc.)
+ await createCollectionExpectSuccess();
+ });
+ });
+
+ it('Add an admin to a collection that has reached the maximum number of admins limit', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const Alice = privateKey('//Alice');
+ const accounts = [
+ 'GsvVmjr1CBHwQHw84pPHMDxgNY3iBLz6Qn7qS3CH8qPhrHz',
+ 'FoQJpPyadYccjavVdTWxpxU7rUEaYhfLCPwXgkfD6Zat9QP',
+ 'JKspFU6ohf1Grg3Phdzj2pSgWvsYWzSfKghhfzMbdhNBWs5',
+ 'Fr4NzY1udSFFLzb2R3qxVQkwz9cZraWkyfH4h3mVVk7BK7P',
+ 'DfnTB4z7eUvYRqcGtTpFsLC69o6tvBSC1pEv8vWPZFtCkaK',
+ 'HnMAUz7r2G8G3hB27SYNyit5aJmh2a5P4eMdDtACtMFDbam',
+ 'DE14BzQ1bDXWPKeLoAqdLAm1GpyAWaWF1knF74cEZeomTBM',
+ ];
+ const collectionId = await createCollectionExpectSuccess();
+
+ const chainLimit = await api.query.nft.chainLimit() as unknown as { CollectionAdminsLimit: BN };
+ const chainAdminLimit = chainLimit.CollectionAdminsLimit.toNumber();
+ expect(chainAdminLimit).to.be.equal(5);
+
+ for (let i = 0; i < chainAdminLimit; i++) {
+ const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, accounts[i]);
+ await submitTransactionAsync(Alice, changeAdminTx);
+ const adminListAfterAddAdmin: any = (await api.query.nft.adminList(collectionId));
+ expect(adminListAfterAddAdmin).to.be.contains(accounts[i]);
+ }
+
+ const tx = api.tx.nft.addCollectionAdmin(collectionId, accounts[chainAdminLimit]);
+ await expect(submitTransactionExpectFailAsync(Alice, tx)).to.be.rejected;
+ });
+ });
+});
tests/src/change-collection-owner.test.tsdiffbeforeafterboth--- a/tests/src/change-collection-owner.test.ts
+++ b/tests/src/change-collection-owner.test.ts
@@ -19,13 +19,13 @@
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
- const collection: any = (await api.query.nft.collection(collectionId));
+ const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
expect(collection.Owner.toString()).to.be.eq(alice.address);
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await submitTransactionAsync(alice, changeOwnerTx);
- const collectionAfterOwnerChange: any = (await api.query.nft.collection(collectionId));
+ const collectionAfterOwnerChange: any = (await api.query.nft.collectionById(collectionId)).toJSON();
expect(collectionAfterOwnerChange.Owner.toString()).to.be.eq(bob.address);
});
});
@@ -41,7 +41,7 @@
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await expect(submitTransactionExpectFailAsync(bob, changeOwnerTx)).to.be.rejected;
- const collectionAfterOwnerChange: any = (await api.query.nft.collection(collectionId));
+ const collectionAfterOwnerChange: any = (await api.query.nft.collectionById(collectionId)).toJSON();
expect(collectionAfterOwnerChange.Owner.toString()).to.be.eq(alice.address);
// Verifying that nothing bad happened (network is live, new collections can be created, etc.)
tests/src/removeCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/removeCollectionAdmin.test.ts
+++ b/tests/src/removeCollectionAdmin.test.ts
@@ -19,7 +19,7 @@
const collectionId = await createCollectionExpectSuccess();
const Alice = privateKey('//Alice');
const Bob = privateKey('//Bob');
- const collection: any = (await api.query.nft.collection(collectionId));
+ const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
expect(collection.Owner.toString()).to.be.eq(Alice.address);
// first - add collection admin Bob
const addAdminTx = api.tx.nft.addCollectionAdmin(collectionId, Bob.address);
tests/src/setCollectionLimits.test.tsdiffbeforeafterboth--- a/tests/src/setCollectionLimits.test.ts
+++ b/tests/src/setCollectionLimits.test.ts
@@ -61,12 +61,12 @@
// tslint:disable-next-line:no-unused-expression
expect(result.success).to.be.true;
- expect(collectionInfo.Limits.AccountTokenOwnershipLimit.toNumber()).to.be.equal(accountTokenOwnershipLimit);
- expect(collectionInfo.Limits.SponsoredMintSize.toNumber()).to.be.equal(sponsoredDataSize);
- expect(collectionInfo.Limits.TokenLimit.toNumber()).to.be.equal(tokenLimit);
- expect(collectionInfo.Limits.SponsorTimeout.toNumber()).to.be.equal(sponsorTimeout);
- expect(collectionInfo.Limits.OwnerCanTransfer.valueOf()).to.be.true;
- expect(collectionInfo.Limits.OwnerCanDestroy.valueOf()).to.be.true;
+ expect(collectionInfo.Limits.AccountTokenOwnershipLimit).to.be.equal(accountTokenOwnershipLimit);
+ expect(collectionInfo.Limits.SponsoredDataSize).to.be.equal(sponsoredDataSize);
+ expect(collectionInfo.Limits.TokenLimit).to.be.equal(tokenLimit);
+ expect(collectionInfo.Limits.SponsorTimeout).to.be.equal(sponsorTimeout);
+ expect(collectionInfo.Limits.OwnerCanTransfer).to.be.true;
+ expect(collectionInfo.Limits.OwnerCanDestroy).to.be.true;
});
});
});
tests/src/setConstOnChainSchema.test.tsdiffbeforeafterboth--- a/tests/src/setConstOnChainSchema.test.ts
+++ b/tests/src/setConstOnChainSchema.test.ts
@@ -36,7 +36,7 @@
it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection: any = (await api.query.nft.collection(collectionId));
+ const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
expect(collection.Owner.toString()).to.be.eq(Alice.address);
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, Shema);
await submitTransactionAsync(Alice, setShema);
@@ -48,7 +48,7 @@
const collectionId = await createCollectionExpectSuccess();
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, Shema);
await submitTransactionAsync(Alice, setShema);
- const collection: any = (await api.query.nft.collection(collectionId));
+ const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
expect(collection.ConstOnChainSchema.toString()).to.be.eq(Shema);
});
@@ -86,7 +86,7 @@
it('Execute method not on behalf of the collection owner', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection: any = (await api.query.nft.collection(collectionId));
+ const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
expect(collection.Owner.toString()).to.be.eq(Alice.address);
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, Shema);
await expect(submitTransactionExpectFailAsync(Bob, setShema)).to.be.rejected;
tests/src/setOffchainSchema.test.tsdiffbeforeafterboth--- a/tests/src/setOffchainSchema.test.ts
+++ b/tests/src/setOffchainSchema.test.ts
@@ -36,7 +36,7 @@
await setOffchainSchemaExpectSuccess(alice, collectionId, DATA);
const collection = await queryCollectionExpectSuccess(collectionId);
- expect(Array.from(collection.OffchainSchema)).to.be.deep.equal(DATA);
+ expect(collection.OffchainSchema).to.be.equal('0x' + Buffer.from(DATA).toString('hex'));
});
});
tests/src/setVariableMetadataSponsoringRateLimit.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/setVariableMetadataSponsoringRateLimit.test.ts
@@ -0,0 +1,80 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+import { IKeyringPair } from '@polkadot/types/types';
+import privateKey from './substrate/privateKey';
+import usingApi from './substrate/substrate-api';
+import {
+ confirmSponsorshipExpectSuccess,
+ createCollectionExpectSuccess,
+ createItemExpectSuccess,
+ findUnusedAddress,
+ setCollectionLimitsExpectSuccess,
+ setCollectionSponsorExpectSuccess,
+ setVariableMetaDataExpectFailure,
+ setVariableMetaDataExpectSuccess,
+} from './util/helpers';
+
+describe('Integration Test setVariableMetadataSponsoringRateLimit', () => {
+ let alice: IKeyringPair;
+ let userWithNoBalance: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async (api) => {
+ alice = privateKey('//Alice');
+ userWithNoBalance = await findUnusedAddress(api);
+ });
+ });
+
+ it('sponsored setVariableMetaData can be called twice with pause for free', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await setCollectionSponsorExpectSuccess(collectionId, alice.address);
+ await confirmSponsorshipExpectSuccess(collectionId);
+ await setCollectionLimitsExpectSuccess(alice, collectionId, {
+ SponsoredDataRateLimit: 0,
+ });
+
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', userWithNoBalance.address);
+ await setVariableMetaDataExpectSuccess(userWithNoBalance, collectionId, itemId, [1, 2, 3]);
+ await setVariableMetaDataExpectSuccess(userWithNoBalance, collectionId, itemId, [1, 2, 3]);
+ });
+
+ it('sponsored setVariableMetaData can\'t be called twice without pause for free', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await setCollectionSponsorExpectSuccess(collectionId, alice.address);
+ await confirmSponsorshipExpectSuccess(collectionId);
+ await setCollectionLimitsExpectSuccess(alice, collectionId, {
+ SponsoredDataRateLimit: 10,
+ });
+
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', userWithNoBalance.address);
+ await setVariableMetaDataExpectSuccess(userWithNoBalance, collectionId, itemId, [1, 2, 3]);
+ await setVariableMetaDataExpectFailure(userWithNoBalance, collectionId, itemId, [1, 2, 3]);
+ });
+
+ it('sponsored setVariableMetaData can\'t be called for free with variable metadata above collection limits', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await setCollectionSponsorExpectSuccess(collectionId, alice.address);
+ await confirmSponsorshipExpectSuccess(collectionId);
+ await setCollectionLimitsExpectSuccess(alice, collectionId, {
+ SponsoredDataRateLimit: 0,
+ SponsoredDataSize: 1,
+ });
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', userWithNoBalance.address);
+
+ await setVariableMetaDataExpectSuccess(userWithNoBalance, collectionId, itemId, [1]);
+ await setVariableMetaDataExpectFailure(userWithNoBalance, collectionId, itemId, [1, 2]);
+ });
+
+ it.only('Default value of rate limit does not sponsor setting variable metadata', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await setCollectionSponsorExpectSuccess(collectionId, alice.address);
+ await confirmSponsorshipExpectSuccess(collectionId);
+
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', userWithNoBalance.address);
+ await setVariableMetaDataExpectFailure(userWithNoBalance, collectionId, itemId, [1]);
+ });
+
+});
tests/src/setVariableOnChainSchema.test.tsdiffbeforeafterboth--- a/tests/src/setVariableOnChainSchema.test.ts
+++ b/tests/src/setVariableOnChainSchema.test.ts
@@ -1,96 +1,96 @@
-//
-// This file is subject to the terms and conditions defined in
-// file 'LICENSE', which is part of this source code package.
-//
-
-import { Keyring } from '@polkadot/api';
-import { IKeyringPair } from '@polkadot/types/types';
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';
-import {
- createCollectionExpectSuccess,
- destroyCollectionExpectSuccess,
-} from './util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-let Alice: IKeyringPair;
-let Bob: IKeyringPair;
-let Schema: any;
-let largeSchema: any;
-
-before(async () => {
- await usingApi(async (api) => {
- const keyring = new Keyring({ type: 'sr25519' });
- Alice = keyring.addFromUri('//Alice');
- Bob = keyring.addFromUri('//Bob');
- Schema = '0x31';
- largeSchema = new Array(4097).fill(0xff);
-
- });
-});
-describe('Integration Test ext. setVariableOnChainSchema()', () => {
-
- it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- const collection: any = (await api.query.nft.collection(collectionId));
- expect(collection.Owner.toString()).to.be.eq(Alice.address);
- const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, Schema);
- await submitTransactionAsync(Alice, setSchema);
- });
- });
-
- it('Checking collection data using the setVariableOnChainSchema parameter', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, Schema);
- await submitTransactionAsync(Alice, setSchema);
- const collection: any = (await api.query.nft.collection(collectionId));
- expect(collection.VariableOnChainSchema.toString()).to.be.eq(Schema);
-
- });
- });
-});
-
-describe('Negative Integration Test ext. setVariableOnChainSchema()', () => {
-
- it('Set a non-existent collection', async () => {
- await usingApi(async (api) => {
- // tslint:disable-next-line: radix
- const collectionId = parseInt((await api.query.nft.createdCollectionCount()).toString()) + 1;
- const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, Schema);
- await expect(submitTransactionExpectFailAsync(Alice, setSchema)).to.be.rejected;
- });
- });
-
- it('Set a previously deleted collection', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- await destroyCollectionExpectSuccess(collectionId);
- const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, Schema);
- await expect(submitTransactionExpectFailAsync(Alice, setSchema)).to.be.rejected;
- });
- });
-
- it('Set invalid data in schema (size too large:> 1024b)', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, largeSchema);
- await expect(submitTransactionExpectFailAsync(Alice, setSchema)).to.be.rejected;
- });
- });
-
- it('Execute method not on behalf of the collection owner', async () => {
- await usingApi(async (api) => {
- const collectionId = await createCollectionExpectSuccess();
- const collection: any = (await api.query.nft.collection(collectionId));
- expect(collection.Owner.toString()).to.be.eq(Alice.address);
- const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, Schema);
- await expect(submitTransactionExpectFailAsync(Bob, setSchema)).to.be.rejected;
- });
- });
-
-});
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+import { Keyring } from '@polkadot/api';
+import { IKeyringPair } from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';
+import {
+ createCollectionExpectSuccess,
+ destroyCollectionExpectSuccess,
+} from './util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+let Alice: IKeyringPair;
+let Bob: IKeyringPair;
+let Schema: any;
+let largeSchema: any;
+
+before(async () => {
+ await usingApi(async (api) => {
+ const keyring = new Keyring({ type: 'sr25519' });
+ Alice = keyring.addFromUri('//Alice');
+ Bob = keyring.addFromUri('//Bob');
+ Schema = '0x31';
+ largeSchema = new Array(4097).fill(0xff);
+
+ });
+});
+describe('Integration Test ext. setVariableOnChainSchema()', () => {
+
+ it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
+ await usingApi(async (api) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
+ expect(collection.Owner.toString()).to.be.eq(Alice.address);
+ const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, Schema);
+ await submitTransactionAsync(Alice, setSchema);
+ });
+ });
+
+ it('Checking collection data using the setVariableOnChainSchema parameter', async () => {
+ await usingApi(async (api) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, Schema);
+ await submitTransactionAsync(Alice, setSchema);
+ const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
+ expect(collection.VariableOnChainSchema.toString()).to.be.eq(Schema);
+
+ });
+ });
+});
+
+describe('Negative Integration Test ext. setVariableOnChainSchema()', () => {
+
+ it('Set a non-existent collection', async () => {
+ await usingApi(async (api) => {
+ // tslint:disable-next-line: radix
+ const collectionId = parseInt((await api.query.nft.createdCollectionCount()).toString()) + 1;
+ const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, Schema);
+ await expect(submitTransactionExpectFailAsync(Alice, setSchema)).to.be.rejected;
+ });
+ });
+
+ it('Set a previously deleted collection', async () => {
+ await usingApi(async (api) => {
+ const collectionId = await createCollectionExpectSuccess();
+ await destroyCollectionExpectSuccess(collectionId);
+ const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, Schema);
+ await expect(submitTransactionExpectFailAsync(Alice, setSchema)).to.be.rejected;
+ });
+ });
+
+ it('Set invalid data in schema (size too large:> 1024b)', async () => {
+ await usingApi(async (api) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, largeSchema);
+ await expect(submitTransactionExpectFailAsync(Alice, setSchema)).to.be.rejected;
+ });
+ });
+
+ it('Execute method not on behalf of the collection owner', async () => {
+ await usingApi(async (api) => {
+ const collectionId = await createCollectionExpectSuccess();
+ const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();
+ expect(collection.Owner.toString()).to.be.eq(Alice.address);
+ const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, Schema);
+ await expect(submitTransactionExpectFailAsync(Bob, setSchema)).to.be.rejected;
+ });
+ });
+
+});
tests/src/types.tsdiffbeforeafterboth--- a/tests/src/types.ts
+++ b/tests/src/types.ts
@@ -13,10 +13,11 @@
Description: [BN, BN]; // utf16
isReFungible: boolean;
Limits: {
- AccountTokenOwnershipLimit: BN;
- SponsoredMintSize: BN;
- TokenLimit: BN;
- SponsorTimeout: BN;
+ AccountTokenOwnershipLimit: number;
+ SponsoredDataSize: number;
+ SponsoredDataRateLimit?: number,
+ TokenLimit: number;
+ SponsorTimeout: number;
OwnerCanTransfer: boolean;
OwnerCanDestroy: boolean;
};
tests/src/util/contracthelpers.tsdiffbeforeafterboth--- a/tests/src/util/contracthelpers.ts
+++ b/tests/src/util/contracthelpers.ts
@@ -22,9 +22,9 @@
function deployContract(alice: IKeyringPair, code: CodePromise, constructor: string = 'default', ...args: any[]): Promise<Contract> {
return new Promise<Contract>(async (resolve, reject) => {
- const unsub = await code
+ const unsub = await (code as any)
.tx[constructor]({value: endowment, gasLimit}, ...args)
- .signAndSend(alice, (result) => {
+ .signAndSend(alice, (result: any) => {
if (result.status.isInBlock || result.status.isFinalized) {
// here we have an additional field in the result, containing the blueprint
resolve((result as any).contract);
tests/src/util/helpers.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { ApiPromise, Keyring } from '@polkadot/api';7import { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { u128 } from '@polkadot/types/primitive';10import { IKeyringPair } from '@polkadot/types/types';11import { BigNumber } from 'bignumber.js';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import { alicesPublicKey, nullPublicKey } from '../accounts';16import privateKey from '../substrate/privateKey';17import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';18import { ICollectionInterface } from '../types';19import { hexToStr, strToUTF16, utf16ToStr } from './util';2021chai.use(chaiAsPromised);22const expect = chai.expect;2324export const U128_MAX = (1n << 128n) - 1n;2526type GenericResult = {27 success: boolean,28};2930interface CreateCollectionResult {31 success: boolean;32 collectionId: number;33}3435interface CreateItemResult {36 success: boolean;37 collectionId: number;38 itemId: number;39 recipient: string;40}4142interface TransferResult {43 success: boolean;44 collectionId: number;45 itemId: number;46 sender: string;47 recipient: string;48 value: bigint;49}5051interface IReFungibleOwner {52 Fraction: BN;53 Owner: number[];54}5556interface ITokenDataType {57 Owner: number[];58 ConstData: number[];59 VariableData: number[];60}6162interface IFungibleTokenDataType {63 Value: BN;64}6566export interface IReFungibleTokenDataType {67 Owner: IReFungibleOwner[];68 ConstData: number[];69 VariableData: number[];70}7172export function getGenericResult(events: EventRecord[]): GenericResult {73 const result: GenericResult = {74 success: false,75 };76 events.forEach(({ phase, event: { data, method, section } }) => {77 // console.log(` ${phase}: ${section}.${method}:: ${data}`);78 if (method === 'ExtrinsicSuccess') {79 result.success = true;80 }81 });82 return result;83}8485export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {86 let success = false;87 let collectionId: number = 0;88 events.forEach(({ phase, event: { data, method, section } }) => {89 // console.log(` ${phase}: ${section}.${method}:: ${data}`);90 if (method == 'ExtrinsicSuccess') {91 success = true;92 } else if ((section == 'nft') && (method == 'Created')) {93 collectionId = parseInt(data[0].toString());94 }95 });96 const result: CreateCollectionResult = {97 success,98 collectionId,99 };100 return result;101}102103export function getCreateItemResult(events: EventRecord[]): CreateItemResult {104 let success = false;105 let collectionId: number = 0;106 let itemId: number = 0;107 let recipient: string = '';108 events.forEach(({ phase, event: { data, method, section } }) => {109 // console.log(` ${phase}: ${section}.${method}:: ${data}`);110 if (method == 'ExtrinsicSuccess') {111 success = true;112 } else if ((section == 'nft') && (method == 'ItemCreated')) {113 collectionId = parseInt(data[0].toString());114 itemId = parseInt(data[1].toString());115 recipient = data[2].toString();116 }117 });118 const result: CreateItemResult = {119 success,120 collectionId,121 itemId,122 recipient,123 };124 return result;125}126127export function getTransferResult(events: EventRecord[]): TransferResult {128 const result: TransferResult = {129 success: false,130 collectionId: 0,131 itemId: 0,132 sender: '',133 recipient: '',134 value: 0n,135 };136137 events.forEach(({event: {data, method, section}}) => {138 if (method === 'ExtrinsicSuccess') {139 result.success = true;140 } else if (section === 'nft' && method === 'Transfer') {141 result.collectionId = +data[0].toString();142 result.itemId = +data[1].toString();143 result.sender = data[2].toString();144 result.recipient = data[3].toString();145 result.value = BigInt(data[4].toString());146 }147 });148149 return result;150}151152interface Invalid {153 type: 'Invalid';154}155156interface Nft {157 type: 'NFT';158}159160interface Fungible {161 type: 'Fungible';162 decimalPoints: number;163}164165interface ReFungible {166 type: 'ReFungible';167}168169type CollectionMode = Nft | Fungible | ReFungible | Invalid;170171export type CreateCollectionParams = {172 mode: CollectionMode,173 name: string,174 description: string,175 tokenPrefix: string,176};177178const defaultCreateCollectionParams: CreateCollectionParams = {179 description: 'description',180 mode: { type: 'NFT' },181 name: 'name',182 tokenPrefix: 'prefix',183}184185export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {186 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};187188 let collectionId: number = 0;189 await usingApi(async (api) => {190 // Get number of collections before the transaction191 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);192193 // Run the CreateCollection transaction194 const alicePrivateKey = privateKey('//Alice');195196 let modeprm = {};197 if (mode.type === 'NFT') {198 modeprm = {nft: null};199 } else if (mode.type === 'Fungible') {200 modeprm = {fungible: mode.decimalPoints};201 } else if (mode.type === 'ReFungible') {202 modeprm = {refungible: null};203 } else if (mode.type === 'Invalid') {204 modeprm = {invalid: null};205 }206207 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);208 const events = await submitTransactionAsync(alicePrivateKey, tx);209 const result = getCreateCollectionResult(events);210211 // Get number of collections after the transaction212 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);213214 // Get the collection215 const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();216217 // What to expect218 // tslint:disable-next-line:no-unused-expression219 expect(result.success).to.be.true;220 expect(result.collectionId).to.be.equal(BcollectionCount);221 // tslint:disable-next-line:no-unused-expression222 expect(collection).to.be.not.null;223 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');224 expect(collection.Owner).to.be.equal(alicesPublicKey);225 expect(utf16ToStr(collection.Name)).to.be.equal(name);226 expect(utf16ToStr(collection.Description)).to.be.equal(description);227 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);228229 collectionId = result.collectionId;230 });231232 return collectionId;233}234235export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {236 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};237238 let modeprm = {};239 if (mode.type === 'NFT') {240 modeprm = {nft: null};241 } else if (mode.type === 'Fungible') {242 modeprm = {fungible: mode.decimalPoints};243 } else if (mode.type === 'ReFungible') {244 modeprm = {refungible: null};245 } else if (mode.type === 'Invalid') {246 modeprm = {invalid: null};247 }248249 await usingApi(async (api) => {250 // Get number of collections before the transaction251 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());252253 // Run the CreateCollection transaction254 const alicePrivateKey = privateKey('//Alice');255 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);256 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;257 const result = getCreateCollectionResult(events);258259 // Get number of collections after the transaction260 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());261262 // What to expect263 // tslint:disable-next-line:no-unused-expression264 expect(result.success).to.be.false;265 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');266 });267}268269export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {270 let bal = new BigNumber(0);271 let unused;272 do {273 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;274 const keyring = new Keyring({ type: 'sr25519' });275 unused = keyring.addFromUri(`//${randomSeed}`);276 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());277 } while (bal.toFixed() != '0');278 return unused;279}280281export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {282 return await usingApi(async (api) => {283 const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;284 return BigInt(bn.toString());285 });286}287288export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {289 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));290}291292export async function findNotExistingCollection(api: ApiPromise): Promise<number> {293 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;294 const newCollection: number = totalNumber + 1;295 return newCollection;296}297298function getDestroyResult(events: EventRecord[]): boolean {299 let success: boolean = false;300 events.forEach(({ phase, event: { data, method, section } }) => {301 // console.log(` ${phase}: ${section}.${method}:: ${data}`);302 if (method == 'ExtrinsicSuccess') {303 success = true;304 }305 });306 return success;307}308309export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {310 await usingApi(async (api) => {311 // Run the DestroyCollection transaction312 const alicePrivateKey = privateKey(senderSeed);313 const tx = api.tx.nft.destroyCollection(collectionId);314 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;315 });316}317318export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {319 await usingApi(async (api) => {320 // Run the DestroyCollection transaction321 const alicePrivateKey = privateKey(senderSeed);322 const tx = api.tx.nft.destroyCollection(collectionId);323 const events = await submitTransactionAsync(alicePrivateKey, tx);324 const result = getDestroyResult(events);325326 // Get the collection327 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();328329 // What to expect330 expect(result).to.be.true;331 expect(collection).to.be.not.null;332 expect(collection.Owner).to.be.equal(nullPublicKey);333 });334}335336export async function queryCollectionLimits(collectionId: number) {337 return await usingApi(async (api) => {338 return ((await api.query.nft.collection(collectionId)).toJSON() as any).Limits;339 });340}341342export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {343 await usingApi(async (api) => {344 const oldLimits = await queryCollectionLimits(collectionId);345 const newLimits = { ...oldLimits as any, ...limits };346 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);347 const events = await submitTransactionAsync(sender, tx);348 const result = getGenericResult(events);349350 expect(result.success).to.be.true;351 });352}353354export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {355 await usingApi(async (api) => {356 const oldLimits = await queryCollectionLimits(collectionId);357 const newLimits = { ...oldLimits as any, ...limits };358 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);359 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;360 const result = getGenericResult(events);361362 expect(result.success).to.be.false;363 });364}365366export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {367 await usingApi(async (api) => {368369 // Run the transaction370 const alicePrivateKey = privateKey('//Alice');371 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);372 const events = await submitTransactionAsync(alicePrivateKey, tx);373 const result = getGenericResult(events);374375 // Get the collection376 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();377378 // What to expect379 expect(result.success).to.be.true;380 expect(collection.Sponsorship).to.deep.equal({381 Unconfirmed: sponsor.toString(),382 });383 });384}385386export async function removeCollectionSponsorExpectSuccess(collectionId: number) {387 await usingApi(async (api) => {388389 // Run the transaction390 const alicePrivateKey = privateKey('//Alice');391 const tx = api.tx.nft.removeCollectionSponsor(collectionId);392 const events = await submitTransactionAsync(alicePrivateKey, tx);393 const result = getGenericResult(events);394395 // Get the collection396 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();397398 // What to expect399 expect(result.success).to.be.true;400 expect(collection.Sponsorship).to.be.deep.equal({ Disabled: null });401 });402}403404export async function removeCollectionSponsorExpectFailure(collectionId: number) {405 await usingApi(async (api) => {406407 // Run the transaction408 const alicePrivateKey = privateKey('//Alice');409 const tx = api.tx.nft.removeCollectionSponsor(collectionId);410 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;411 });412}413414export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {415 await usingApi(async (api) => {416417 // Run the transaction418 const alicePrivateKey = privateKey(senderSeed);419 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);420 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;421 });422}423424export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {425 await usingApi(async (api) => {426427 // Run the transaction428 const sender = privateKey(senderSeed);429 const tx = api.tx.nft.confirmSponsorship(collectionId);430 const events = await submitTransactionAsync(sender, tx);431 const result = getGenericResult(events);432433 // Get the collection434 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();435436 // What to expect437 expect(result.success).to.be.true;438 expect(collection.Sponsorship).to.be.deep.equal({439 Confirmed: sender.address,440 });441 });442}443444445export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {446 await usingApi(async (api) => {447448 // Run the transaction449 const sender = privateKey(senderSeed);450 const tx = api.tx.nft.confirmSponsorship(collectionId);451 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;452 });453}454455export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {456 await usingApi(async (api) => {457 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);458 const events = await submitTransactionAsync(sender, tx);459 const result = getGenericResult(events);460461 expect(result.success).to.be.true;462 });463}464465export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {466 await usingApi(async (api) => {467 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);468 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;469 const result = getGenericResult(events);470471 expect(result.success).to.be.false;472 });473}474475export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {476 await usingApi(async (api) => {477 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);478 const events = await submitTransactionAsync(sender, tx);479 const result = getGenericResult(events);480481 expect(result.success).to.be.true;482 });483}484485export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {486 await usingApi(async (api) => {487 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);488 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;489 const result = getGenericResult(events);490491 expect(result.success).to.be.false;492 });493}494495export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {496 await usingApi(async (api) => {497 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);498 const events = await submitTransactionAsync(sender, tx);499 const result = getGenericResult(events);500501 expect(result.success).to.be.true;502 });503}504505export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {506 let whitelisted: boolean = false;507 await usingApi(async (api) => {508 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;509 });510 return whitelisted;511}512513export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {514 await usingApi(async (api) => {515 const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);516 const events = await submitTransactionAsync(sender, tx);517 const result = getGenericResult(events);518519 expect(result.success).to.be.true;520 });521}522523export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {524 await usingApi(async (api) => {525 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);526 const events = await submitTransactionAsync(sender, tx);527 const result = getGenericResult(events);528529 expect(result.success).to.be.true;530 });531}532533export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {534 await usingApi(async (api) => {535 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);536 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;537 const result = getGenericResult(events);538539 expect(result.success).to.be.false;540 });541}542543export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {544 await usingApi(async (api) => {545 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));546 const events = await submitTransactionAsync(sender, tx);547 const result = getGenericResult(events);548549 expect(result.success).to.be.true;550 });551}552553export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {554 await usingApi(async (api) => {555 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));556 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;557 });558}559560export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {561 await usingApi(async (api) => {562 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));563 const events = await submitTransactionAsync(sender, tx);564 const result = getGenericResult(events);565566 expect(result.success).to.be.true;567 });568}569570export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {571 await usingApi(async (api) => {572 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));573 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;574 });575}576577export interface CreateFungibleData {578 readonly Value: bigint;579}580581export interface CreateReFungibleData { }582export interface CreateNftData { }583584export type CreateItemData = {585 NFT: CreateNftData;586} | {587 Fungible: CreateFungibleData;588} | {589 ReFungible: CreateReFungibleData;590};591592export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {593 await usingApi(async (api) => {594 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);595 const events = await submitTransactionAsync(owner, tx);596 const result = getGenericResult(events);597 // Get the item598 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();599 // What to expect600 // tslint:disable-next-line:no-unused-expression601 expect(result.success).to.be.true;602 // tslint:disable-next-line:no-unused-expression603 expect(item).to.be.not.null;604 expect(item.Owner).to.be.equal(nullPublicKey);605 });606}607608export async function609approveExpectSuccess(collectionId: number,610 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {611 await usingApi(async (api: ApiPromise) => {612 const allowanceBefore =613 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;614 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);615 const events = await submitTransactionAsync(owner, approveNftTx);616 const result = getCreateItemResult(events);617 // tslint:disable-next-line:no-unused-expression618 expect(result.success).to.be.true;619 const allowanceAfter =620 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;621 expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());622 });623}624625export async function626transferFromExpectSuccess(collectionId: number,627 tokenId: number,628 accountApproved: IKeyringPair,629 accountFrom: IKeyringPair,630 accountTo: IKeyringPair,631 value: number | bigint = 1,632 type: string = 'NFT') {633 await usingApi(async (api: ApiPromise) => {634 let balanceBefore = new BN(0);635 if (type === 'Fungible') {636 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;637 }638 const transferFromTx = await api.tx.nft.transferFrom(639 accountFrom.address, accountTo.address, collectionId, tokenId, value);640 const events = await submitTransactionAsync(accountApproved, transferFromTx);641 const result = getCreateItemResult(events);642 // tslint:disable-next-line:no-unused-expression643 expect(result.success).to.be.true;644 if (type === 'NFT') {645 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;646 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);647 }648 if (type === 'Fungible') {649 const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;650 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());651 }652 if (type === 'ReFungible') {653 const nftItemData =654 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;655 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);656 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);657 }658 });659}660661export async function662transferFromExpectFail(collectionId: number,663 tokenId: number,664 accountApproved: IKeyringPair,665 accountFrom: IKeyringPair,666 accountTo: IKeyringPair,667 value: number | bigint = 1) {668 await usingApi(async (api: ApiPromise) => {669 const transferFromTx = await api.tx.nft.transferFrom(670 accountFrom.address, accountTo.address, collectionId, tokenId, value);671 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;672 const result = getCreateCollectionResult(events);673 // tslint:disable-next-line:no-unused-expression674 expect(result.success).to.be.false;675 });676}677678export async function679transferExpectSuccess(collectionId: number,680 tokenId: number,681 sender: IKeyringPair,682 recipient: IKeyringPair,683 value: number | bigint = 1,684 type: string = 'NFT') {685 await usingApi(async (api: ApiPromise) => {686 let balanceBefore = new BN(0);687 if (type === 'Fungible') {688 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;689 }690 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);691 const events = await submitTransactionAsync(sender, transferTx);692 const result = getTransferResult(events);693 // tslint:disable-next-line:no-unused-expression694 expect(result.success).to.be.true;695 expect(result.collectionId).to.be.equal(collectionId);696 expect(result.itemId).to.be.equal(tokenId);697 expect(result.sender).to.be.equal(sender.address);698 expect(result.recipient).to.be.equal(recipient.address);699 expect(result.value.toString()).to.be.equal(value.toString());700 if (type === 'NFT') {701 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;702 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);703 }704 if (type === 'Fungible') {705 const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;706 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());707 }708 if (type === 'ReFungible') {709 const nftItemData =710 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;711 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);712 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);713 }714 });715}716717export async function718transferExpectFail(collectionId: number,719 tokenId: number,720 sender: IKeyringPair,721 recipient: IKeyringPair,722 value: number | bigint = 1,723 type: string = 'NFT') {724 await usingApi(async (api: ApiPromise) => {725 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);726 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;727 if (events && Array.isArray(events)) {728 const result = getCreateCollectionResult(events);729 // tslint:disable-next-line:no-unused-expression730 expect(result.success).to.be.false;731 }732 });733}734735export async function736approveExpectFail(collectionId: number,737 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {738 await usingApi(async (api: ApiPromise) => {739 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);740 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;741 const result = getCreateCollectionResult(events);742 // tslint:disable-next-line:no-unused-expression743 expect(result.success).to.be.false;744 });745}746747export async function getFungibleBalance(748 collectionId: number,749 owner: string,750) {751 return await usingApi(async (api) => {752 const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};753 return BigInt(response.Value);754 });755}756757export async function createFungibleItemExpectSuccess(758 sender: IKeyringPair,759 collectionId: number,760 data: CreateFungibleData,761 owner: string = sender.address,762) {763 return await usingApi(async (api) => {764 const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });765766 const events = await submitTransactionAsync(sender, tx);767 const result = getCreateItemResult(events);768769 expect(result.success).to.be.true;770 return result.itemId;771 });772}773774export async function createItemExpectSuccess(775 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {776 let newItemId: number = 0;777 await usingApi(async (api) => {778 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);779 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();780 const AItemBalance = new BigNumber(Aitem.Value);781782 if (owner === '') {783 owner = sender.address;784 }785786 let tx;787 if (createMode === 'Fungible') {788 const createData = {fungible: {value: 10}};789 tx = api.tx.nft.createItem(collectionId, owner, createData);790 } else if (createMode === 'ReFungible') {791 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};792 tx = api.tx.nft.createItem(collectionId, owner, createData);793 } else {794 tx = api.tx.nft.createItem(collectionId, owner, createMode);795 }796 const events = await submitTransactionAsync(sender, tx);797 const result = getCreateItemResult(events);798799 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);800 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();801 const BItemBalance = new BigNumber(Bitem.Value);802803 // What to expect804 // tslint:disable-next-line:no-unused-expression805 expect(result.success).to.be.true;806 if (createMode === 'Fungible') {807 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);808 } else {809 expect(BItemCount).to.be.equal(AItemCount + 1);810 }811 expect(collectionId).to.be.equal(result.collectionId);812 expect(BItemCount).to.be.equal(result.itemId);813 expect(owner).to.be.equal(result.recipient);814 newItemId = result.itemId;815 });816 return newItemId;817}818819export async function createItemExpectFailure(820 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {821 await usingApi(async (api) => {822 const tx = api.tx.nft.createItem(collectionId, owner, createMode);823 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;824 const result = getCreateItemResult(events);825826 expect(result.success).to.be.false;827 });828}829830export async function setPublicAccessModeExpectSuccess(831 sender: IKeyringPair, collectionId: number,832 accessMode: 'Normal' | 'WhiteList',833) {834 await usingApi(async (api) => {835836 // Run the transaction837 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);838 const events = await submitTransactionAsync(sender, tx);839 const result = getGenericResult(events);840841 // Get the collection842 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();843844 // What to expect845 // tslint:disable-next-line:no-unused-expression846 expect(result.success).to.be.true;847 expect(collection.Access).to.be.equal(accessMode);848 });849}850851export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {852 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');853}854855export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {856 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');857}858859export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {860 await usingApi(async (api) => {861862 // Run the transaction863 const tx = api.tx.nft.setMintPermission(collectionId, enabled);864 const events = await submitTransactionAsync(sender, tx);865 const result = getGenericResult(events);866867 // Get the collection868 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();869870 // What to expect871 // tslint:disable-next-line:no-unused-expression872 expect(result.success).to.be.true;873 expect(collection.MintMode).to.be.equal(enabled);874 });875}876877export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {878 await setMintPermissionExpectSuccess(sender, collectionId, true);879}880881export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {882 await usingApi(async (api) => {883 // Run the transaction884 const tx = api.tx.nft.setMintPermission(collectionId, enabled);885 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;886 const result = getCreateCollectionResult(events);887 // tslint:disable-next-line:no-unused-expression888 expect(result.success).to.be.false;889 });890}891892export async function isWhitelisted(collectionId: number, address: string) {893 let whitelisted: boolean = false;894 await usingApi(async (api) => {895 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;896 });897 return whitelisted;898}899900export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {901 await usingApi(async (api) => {902903 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();904905 // Run the transaction906 const tx = api.tx.nft.addToWhiteList(collectionId, address);907 const events = await submitTransactionAsync(sender, tx);908 const result = getGenericResult(events);909910 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();911912 // What to expect913 // tslint:disable-next-line:no-unused-expression914 expect(result.success).to.be.true;915 // tslint:disable-next-line: no-unused-expression916 expect(whiteListedBefore).to.be.false;917 // tslint:disable-next-line: no-unused-expression918 expect(whiteListedAfter).to.be.true;919 });920}921922export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {923 await usingApi(async (api) => {924 // Run the transaction925 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);926 const events = await submitTransactionAsync(sender, tx);927 const result = getGenericResult(events);928929 // What to expect930 // tslint:disable-next-line:no-unused-expression931 expect(result.success).to.be.true;932 });933}934935export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {936 await usingApi(async (api) => {937 // Run the transaction938 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);939 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;940 const result = getGenericResult(events);941942 // What to expect943 // tslint:disable-next-line:no-unused-expression944 expect(result.success).to.be.false;945 });946}947948export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)949 : Promise<ICollectionInterface | null> => {950 return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;951};952953export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {954 // set global object - collectionsCount955 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();956};957958export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {959 return await usingApi(async (api) => {960 return (await api.query.nft.collection(collectionId)) as unknown as ICollectionInterface;961 });962}1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { ApiPromise, Keyring } from '@polkadot/api';7import { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { u128 } from '@polkadot/types/primitive';10import { IKeyringPair } from '@polkadot/types/types';11import { BigNumber } from 'bignumber.js';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import { alicesPublicKey, nullPublicKey } from '../accounts';16import privateKey from '../substrate/privateKey';17import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';18import { ICollectionInterface } from '../types';19import { hexToStr, strToUTF16, utf16ToStr } from './util';2021chai.use(chaiAsPromised);22const expect = chai.expect;2324export const U128_MAX = (1n << 128n) - 1n;2526type GenericResult = {27 success: boolean,28};2930interface CreateCollectionResult {31 success: boolean;32 collectionId: number;33}3435interface CreateItemResult {36 success: boolean;37 collectionId: number;38 itemId: number;39 recipient: string;40}4142interface TransferResult {43 success: boolean;44 collectionId: number;45 itemId: number;46 sender: string;47 recipient: string;48 value: bigint;49}5051interface IReFungibleOwner {52 Fraction: BN;53 Owner: number[];54}5556interface ITokenDataType {57 Owner: number[];58 ConstData: number[];59 VariableData: number[];60}6162interface IFungibleTokenDataType {63 Value: BN;64}6566export interface IReFungibleTokenDataType {67 Owner: IReFungibleOwner[];68 ConstData: number[];69 VariableData: number[];70}7172export function getGenericResult(events: EventRecord[]): GenericResult {73 const result: GenericResult = {74 success: false,75 };76 events.forEach(({ phase, event: { data, method, section } }) => {77 // console.log(` ${phase}: ${section}.${method}:: ${data}`);78 if (method === 'ExtrinsicSuccess') {79 result.success = true;80 }81 });82 return result;83}8485export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {86 let success = false;87 let collectionId: number = 0;88 events.forEach(({ phase, event: { data, method, section } }) => {89 // console.log(` ${phase}: ${section}.${method}:: ${data}`);90 if (method == 'ExtrinsicSuccess') {91 success = true;92 } else if ((section == 'nft') && (method == 'Created')) {93 collectionId = parseInt(data[0].toString());94 }95 });96 const result: CreateCollectionResult = {97 success,98 collectionId,99 };100 return result;101}102103export function getCreateItemResult(events: EventRecord[]): CreateItemResult {104 let success = false;105 let collectionId: number = 0;106 let itemId: number = 0;107 let recipient: string = '';108 events.forEach(({ phase, event: { data, method, section } }) => {109 // console.log(` ${phase}: ${section}.${method}:: ${data}`);110 if (method == 'ExtrinsicSuccess') {111 success = true;112 } else if ((section == 'nft') && (method == 'ItemCreated')) {113 collectionId = parseInt(data[0].toString());114 itemId = parseInt(data[1].toString());115 recipient = data[2].toString();116 }117 });118 const result: CreateItemResult = {119 success,120 collectionId,121 itemId,122 recipient,123 };124 return result;125}126127export function getTransferResult(events: EventRecord[]): TransferResult {128 const result: TransferResult = {129 success: false,130 collectionId: 0,131 itemId: 0,132 sender: '',133 recipient: '',134 value: 0n,135 };136137 events.forEach(({event: {data, method, section}}) => {138 if (method === 'ExtrinsicSuccess') {139 result.success = true;140 } else if (section === 'nft' && method === 'Transfer') {141 result.collectionId = +data[0].toString();142 result.itemId = +data[1].toString();143 result.sender = data[2].toString();144 result.recipient = data[3].toString();145 result.value = BigInt(data[4].toString());146 }147 });148149 return result;150}151152interface Invalid {153 type: 'Invalid';154}155156interface Nft {157 type: 'NFT';158}159160interface Fungible {161 type: 'Fungible';162 decimalPoints: number;163}164165interface ReFungible {166 type: 'ReFungible';167}168169type CollectionMode = Nft | Fungible | ReFungible | Invalid;170171export type CreateCollectionParams = {172 mode: CollectionMode,173 name: string,174 description: string,175 tokenPrefix: string,176};177178const defaultCreateCollectionParams: CreateCollectionParams = {179 description: 'description',180 mode: { type: 'NFT' },181 name: 'name',182 tokenPrefix: 'prefix',183}184185export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {186 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};187188 let collectionId: number = 0;189 await usingApi(async (api) => {190 // Get number of collections before the transaction191 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);192193 // Run the CreateCollection transaction194 const alicePrivateKey = privateKey('//Alice');195196 let modeprm = {};197 if (mode.type === 'NFT') {198 modeprm = {nft: null};199 } else if (mode.type === 'Fungible') {200 modeprm = {fungible: mode.decimalPoints};201 } else if (mode.type === 'ReFungible') {202 modeprm = {refungible: null};203 } else if (mode.type === 'Invalid') {204 modeprm = {invalid: null};205 }206207 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);208 const events = await submitTransactionAsync(alicePrivateKey, tx);209 const result = getCreateCollectionResult(events);210211 // Get number of collections after the transaction212 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);213214 // Get the collection215 const collection: any = (await api.query.nft.collectionById(result.collectionId)).toJSON();216217 // What to expect218 // tslint:disable-next-line:no-unused-expression219 expect(result.success).to.be.true;220 expect(result.collectionId).to.be.equal(BcollectionCount);221 // tslint:disable-next-line:no-unused-expression222 expect(collection).to.be.not.null;223 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');224 expect(collection.Owner).to.be.equal(alicesPublicKey);225 expect(utf16ToStr(collection.Name)).to.be.equal(name);226 expect(utf16ToStr(collection.Description)).to.be.equal(description);227 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);228229 collectionId = result.collectionId;230 });231232 return collectionId;233}234235export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {236 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};237238 let modeprm = {};239 if (mode.type === 'NFT') {240 modeprm = {nft: null};241 } else if (mode.type === 'Fungible') {242 modeprm = {fungible: mode.decimalPoints};243 } else if (mode.type === 'ReFungible') {244 modeprm = {refungible: null};245 } else if (mode.type === 'Invalid') {246 modeprm = {invalid: null};247 }248249 await usingApi(async (api) => {250 // Get number of collections before the transaction251 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());252253 // Run the CreateCollection transaction254 const alicePrivateKey = privateKey('//Alice');255 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);256 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;257 const result = getCreateCollectionResult(events);258259 // Get number of collections after the transaction260 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());261262 // What to expect263 // tslint:disable-next-line:no-unused-expression264 expect(result.success).to.be.false;265 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');266 });267}268269export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {270 let bal = new BigNumber(0);271 let unused;272 do {273 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;274 const keyring = new Keyring({ type: 'sr25519' });275 unused = keyring.addFromUri(`//${randomSeed}`);276 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());277 } while (bal.toFixed() != '0');278 return unused;279}280281export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {282 return await usingApi(async (api) => {283 const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;284 return BigInt(bn.toString());285 });286}287288export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {289 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));290}291292export async function findNotExistingCollection(api: ApiPromise): Promise<number> {293 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;294 const newCollection: number = totalNumber + 1;295 return newCollection;296}297298function getDestroyResult(events: EventRecord[]): boolean {299 let success: boolean = false;300 events.forEach(({ phase, event: { data, method, section } }) => {301 // console.log(` ${phase}: ${section}.${method}:: ${data}`);302 if (method == 'ExtrinsicSuccess') {303 success = true;304 }305 });306 return success;307}308309export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {310 await usingApi(async (api) => {311 // Run the DestroyCollection transaction312 const alicePrivateKey = privateKey(senderSeed);313 const tx = api.tx.nft.destroyCollection(collectionId);314 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;315 });316}317318export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {319 await usingApi(async (api) => {320 // Run the DestroyCollection transaction321 const alicePrivateKey = privateKey(senderSeed);322 const tx = api.tx.nft.destroyCollection(collectionId);323 const events = await submitTransactionAsync(alicePrivateKey, tx);324 const result = getDestroyResult(events);325326 // Get the collection327 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();328329 // What to expect330 expect(result).to.be.true;331 expect(collection).to.be.null;332 });333}334335export async function queryCollectionLimits(collectionId: number) {336 return await usingApi(async (api) => {337 return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;338 });339}340341export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {342 await usingApi(async (api) => {343 const oldLimits = await queryCollectionLimits(collectionId);344 const newLimits = { ...oldLimits as any, ...limits };345 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);346 const events = await submitTransactionAsync(sender, tx);347 const result = getGenericResult(events);348349 expect(result.success).to.be.true;350 });351}352353export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {354 await usingApi(async (api) => {355 const oldLimits = await queryCollectionLimits(collectionId);356 const newLimits = { ...oldLimits as any, ...limits };357 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);358 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;359 const result = getGenericResult(events);360361 expect(result.success).to.be.false;362 });363}364365export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {366 await usingApi(async (api) => {367368 // Run the transaction369 const alicePrivateKey = privateKey('//Alice');370 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);371 const events = await submitTransactionAsync(alicePrivateKey, tx);372 const result = getGenericResult(events);373374 // Get the collection375 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();376377 // What to expect378 expect(result.success).to.be.true;379 expect(collection.Sponsorship).to.deep.equal({380 Unconfirmed: sponsor.toString(),381 });382 });383}384385export async function removeCollectionSponsorExpectSuccess(collectionId: number) {386 await usingApi(async (api) => {387388 // Run the transaction389 const alicePrivateKey = privateKey('//Alice');390 const tx = api.tx.nft.removeCollectionSponsor(collectionId);391 const events = await submitTransactionAsync(alicePrivateKey, tx);392 const result = getGenericResult(events);393394 // Get the collection395 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();396397 // What to expect398 expect(result.success).to.be.true;399 expect(collection.Sponsorship).to.be.deep.equal({ Disabled: null });400 });401}402403export async function removeCollectionSponsorExpectFailure(collectionId: number) {404 await usingApi(async (api) => {405406 // Run the transaction407 const alicePrivateKey = privateKey('//Alice');408 const tx = api.tx.nft.removeCollectionSponsor(collectionId);409 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;410 });411}412413export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {414 await usingApi(async (api) => {415416 // Run the transaction417 const alicePrivateKey = privateKey(senderSeed);418 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);419 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;420 });421}422423export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {424 await usingApi(async (api) => {425426 // Run the transaction427 const sender = privateKey(senderSeed);428 const tx = api.tx.nft.confirmSponsorship(collectionId);429 const events = await submitTransactionAsync(sender, tx);430 const result = getGenericResult(events);431432 // Get the collection433 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();434435 // What to expect436 expect(result.success).to.be.true;437 expect(collection.Sponsorship).to.be.deep.equal({438 Confirmed: sender.address,439 });440 });441}442443444export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {445 await usingApi(async (api) => {446447 // Run the transaction448 const sender = privateKey(senderSeed);449 const tx = api.tx.nft.confirmSponsorship(collectionId);450 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;451 });452}453454export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {455 await usingApi(async (api) => {456 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);457 const events = await submitTransactionAsync(sender, tx);458 const result = getGenericResult(events);459460 expect(result.success).to.be.true;461 });462}463464export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {465 await usingApi(async (api) => {466 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);467 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;468 const result = getGenericResult(events);469470 expect(result.success).to.be.false;471 });472}473474export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {475 await usingApi(async (api) => {476 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);477 const events = await submitTransactionAsync(sender, tx);478 const result = getGenericResult(events);479480 expect(result.success).to.be.true;481 });482}483484export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {485 await usingApi(async (api) => {486 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);487 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;488 const result = getGenericResult(events);489490 expect(result.success).to.be.false;491 });492}493494export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {495 await usingApi(async (api) => {496 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);497 const events = await submitTransactionAsync(sender, tx);498 const result = getGenericResult(events);499500 expect(result.success).to.be.true;501 });502}503504export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {505 let whitelisted: boolean = false;506 await usingApi(async (api) => {507 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;508 });509 return whitelisted;510}511512export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {513 await usingApi(async (api) => {514 const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);515 const events = await submitTransactionAsync(sender, tx);516 const result = getGenericResult(events);517518 expect(result.success).to.be.true;519 });520}521522export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {523 await usingApi(async (api) => {524 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);525 const events = await submitTransactionAsync(sender, tx);526 const result = getGenericResult(events);527528 expect(result.success).to.be.true;529 });530}531532export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {533 await usingApi(async (api) => {534 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);535 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;536 const result = getGenericResult(events);537538 expect(result.success).to.be.false;539 });540}541542export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {543 await usingApi(async (api) => {544 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));545 const events = await submitTransactionAsync(sender, tx);546 const result = getGenericResult(events);547548 expect(result.success).to.be.true;549 });550}551552export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {553 await usingApi(async (api) => {554 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));555 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;556 });557}558559export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {560 await usingApi(async (api) => {561 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));562 const events = await submitTransactionAsync(sender, tx);563 const result = getGenericResult(events);564565 expect(result.success).to.be.true;566 });567}568569export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {570 await usingApi(async (api) => {571 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));572 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;573 });574}575576export interface CreateFungibleData {577 readonly Value: bigint;578}579580export interface CreateReFungibleData { }581export interface CreateNftData { }582583export type CreateItemData = {584 NFT: CreateNftData;585} | {586 Fungible: CreateFungibleData;587} | {588 ReFungible: CreateReFungibleData;589};590591export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {592 await usingApi(async (api) => {593 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);594 const events = await submitTransactionAsync(owner, tx);595 const result = getGenericResult(events);596 // Get the item597 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();598 // What to expect599 // tslint:disable-next-line:no-unused-expression600 expect(result.success).to.be.true;601 // tslint:disable-next-line:no-unused-expression602 expect(item).to.be.not.null;603 expect(item.Owner).to.be.equal(nullPublicKey);604 });605}606607export async function608approveExpectSuccess(collectionId: number,609 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {610 await usingApi(async (api: ApiPromise) => {611 const allowanceBefore =612 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;613 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);614 const events = await submitTransactionAsync(owner, approveNftTx);615 const result = getCreateItemResult(events);616 // tslint:disable-next-line:no-unused-expression617 expect(result.success).to.be.true;618 const allowanceAfter =619 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;620 expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());621 });622}623624export async function625transferFromExpectSuccess(collectionId: number,626 tokenId: number,627 accountApproved: IKeyringPair,628 accountFrom: IKeyringPair,629 accountTo: IKeyringPair,630 value: number | bigint = 1,631 type: string = 'NFT') {632 await usingApi(async (api: ApiPromise) => {633 let balanceBefore = new BN(0);634 if (type === 'Fungible') {635 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;636 }637 const transferFromTx = await api.tx.nft.transferFrom(638 accountFrom.address, accountTo.address, collectionId, tokenId, value);639 const events = await submitTransactionAsync(accountApproved, transferFromTx);640 const result = getCreateItemResult(events);641 // tslint:disable-next-line:no-unused-expression642 expect(result.success).to.be.true;643 if (type === 'NFT') {644 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;645 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);646 }647 if (type === 'Fungible') {648 const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;649 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());650 }651 if (type === 'ReFungible') {652 const nftItemData =653 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;654 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);655 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);656 }657 });658}659660export async function661transferFromExpectFail(collectionId: number,662 tokenId: number,663 accountApproved: IKeyringPair,664 accountFrom: IKeyringPair,665 accountTo: IKeyringPair,666 value: number | bigint = 1) {667 await usingApi(async (api: ApiPromise) => {668 const transferFromTx = await api.tx.nft.transferFrom(669 accountFrom.address, accountTo.address, collectionId, tokenId, value);670 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;671 const result = getCreateCollectionResult(events);672 // tslint:disable-next-line:no-unused-expression673 expect(result.success).to.be.false;674 });675}676677export async function678transferExpectSuccess(collectionId: number,679 tokenId: number,680 sender: IKeyringPair,681 recipient: IKeyringPair,682 value: number | bigint = 1,683 type: string = 'NFT') {684 await usingApi(async (api: ApiPromise) => {685 let balanceBefore = new BN(0);686 if (type === 'Fungible') {687 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;688 }689 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);690 const events = await submitTransactionAsync(sender, transferTx);691 const result = getTransferResult(events);692 // tslint:disable-next-line:no-unused-expression693 expect(result.success).to.be.true;694 expect(result.collectionId).to.be.equal(collectionId);695 expect(result.itemId).to.be.equal(tokenId);696 expect(result.sender).to.be.equal(sender.address);697 expect(result.recipient).to.be.equal(recipient.address);698 expect(result.value.toString()).to.be.equal(value.toString());699 if (type === 'NFT') {700 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;701 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);702 }703 if (type === 'Fungible') {704 const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;705 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());706 }707 if (type === 'ReFungible') {708 const nftItemData =709 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;710 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);711 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);712 }713 });714}715716export async function717transferExpectFail(collectionId: number,718 tokenId: number,719 sender: IKeyringPair,720 recipient: IKeyringPair,721 value: number | bigint = 1,722 type: string = 'NFT') {723 await usingApi(async (api: ApiPromise) => {724 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);725 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;726 if (events && Array.isArray(events)) {727 const result = getCreateCollectionResult(events);728 // tslint:disable-next-line:no-unused-expression729 expect(result.success).to.be.false;730 }731 });732}733734export async function735approveExpectFail(collectionId: number,736 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {737 await usingApi(async (api: ApiPromise) => {738 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);739 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;740 const result = getCreateCollectionResult(events);741 // tslint:disable-next-line:no-unused-expression742 expect(result.success).to.be.false;743 });744}745746export async function getFungibleBalance(747 collectionId: number,748 owner: string,749) {750 return await usingApi(async (api) => {751 const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};752 return BigInt(response.Value);753 });754}755756export async function createFungibleItemExpectSuccess(757 sender: IKeyringPair,758 collectionId: number,759 data: CreateFungibleData,760 owner: string = sender.address,761) {762 return await usingApi(async (api) => {763 const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });764765 const events = await submitTransactionAsync(sender, tx);766 const result = getCreateItemResult(events);767768 expect(result.success).to.be.true;769 return result.itemId;770 });771}772773export async function createItemExpectSuccess(774 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {775 let newItemId: number = 0;776 await usingApi(async (api) => {777 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);778 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();779 const AItemBalance = new BigNumber(Aitem.Value);780781 if (owner === '') {782 owner = sender.address;783 }784785 let tx;786 if (createMode === 'Fungible') {787 const createData = {fungible: {value: 10}};788 tx = api.tx.nft.createItem(collectionId, owner, createData);789 } else if (createMode === 'ReFungible') {790 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};791 tx = api.tx.nft.createItem(collectionId, owner, createData);792 } else {793 tx = api.tx.nft.createItem(collectionId, owner, createMode);794 }795 const events = await submitTransactionAsync(sender, tx);796 const result = getCreateItemResult(events);797798 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);799 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();800 const BItemBalance = new BigNumber(Bitem.Value);801802 // What to expect803 // tslint:disable-next-line:no-unused-expression804 expect(result.success).to.be.true;805 if (createMode === 'Fungible') {806 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);807 } else {808 expect(BItemCount).to.be.equal(AItemCount + 1);809 }810 expect(collectionId).to.be.equal(result.collectionId);811 expect(BItemCount).to.be.equal(result.itemId);812 expect(owner).to.be.equal(result.recipient);813 newItemId = result.itemId;814 });815 return newItemId;816}817818export async function createItemExpectFailure(819 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {820 await usingApi(async (api) => {821 const tx = api.tx.nft.createItem(collectionId, owner, createMode);822 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;823 const result = getCreateItemResult(events);824825 expect(result.success).to.be.false;826 });827}828829export async function setPublicAccessModeExpectSuccess(830 sender: IKeyringPair, collectionId: number,831 accessMode: 'Normal' | 'WhiteList',832) {833 await usingApi(async (api) => {834835 // Run the transaction836 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);837 const events = await submitTransactionAsync(sender, tx);838 const result = getGenericResult(events);839840 // Get the collection841 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();842843 // What to expect844 // tslint:disable-next-line:no-unused-expression845 expect(result.success).to.be.true;846 expect(collection.Access).to.be.equal(accessMode);847 });848}849850export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {851 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');852}853854export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {855 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');856}857858export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {859 await usingApi(async (api) => {860861 // Run the transaction862 const tx = api.tx.nft.setMintPermission(collectionId, enabled);863 const events = await submitTransactionAsync(sender, tx);864 const result = getGenericResult(events);865866 // Get the collection867 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();868869 // What to expect870 // tslint:disable-next-line:no-unused-expression871 expect(result.success).to.be.true;872 expect(collection.MintMode).to.be.equal(enabled);873 });874}875876export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {877 await setMintPermissionExpectSuccess(sender, collectionId, true);878}879880export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {881 await usingApi(async (api) => {882 // Run the transaction883 const tx = api.tx.nft.setMintPermission(collectionId, enabled);884 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;885 const result = getCreateCollectionResult(events);886 // tslint:disable-next-line:no-unused-expression887 expect(result.success).to.be.false;888 });889}890891export async function isWhitelisted(collectionId: number, address: string) {892 let whitelisted: boolean = false;893 await usingApi(async (api) => {894 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;895 });896 return whitelisted;897}898899export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {900 await usingApi(async (api) => {901902 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();903904 // Run the transaction905 const tx = api.tx.nft.addToWhiteList(collectionId, address);906 const events = await submitTransactionAsync(sender, tx);907 const result = getGenericResult(events);908909 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();910911 // What to expect912 // tslint:disable-next-line:no-unused-expression913 expect(result.success).to.be.true;914 // tslint:disable-next-line: no-unused-expression915 expect(whiteListedBefore).to.be.false;916 // tslint:disable-next-line: no-unused-expression917 expect(whiteListedAfter).to.be.true;918 });919}920921export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {922 await usingApi(async (api) => {923 // Run the transaction924 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);925 const events = await submitTransactionAsync(sender, tx);926 const result = getGenericResult(events);927928 // What to expect929 // tslint:disable-next-line:no-unused-expression930 expect(result.success).to.be.true;931 });932}933934export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {935 await usingApi(async (api) => {936 // Run the transaction937 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);938 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;939 const result = getGenericResult(events);940941 // What to expect942 // tslint:disable-next-line:no-unused-expression943 expect(result.success).to.be.false;944 });945}946947export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)948 : Promise<ICollectionInterface | null> => {949 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;950};951952export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {953 // set global object - collectionsCount954 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();955};956957export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {958 return await usingApi(async (api) => {959 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;960 });961}