difftreelog
Merge pull request #130 from usetech-llc/NFTPAR-310_builders_review_107
in: master
Review changes
9 files changed
node/src/chain_spec.rsdiffbeforeafterboth--- a/node/src/chain_spec.rs
+++ b/node/src/chain_spec.rs
@@ -193,8 +193,7 @@
mint_mode: false,
offchain_schema: vec![],
schema_version: SchemaVersion::default(),
- sponsor: get_account_id_from_seed::<sr25519::Public>("Alice"),
- sponsor_confirmed: true,
+ sponsorship: SponsorshipState::Confirmed(get_account_id_from_seed::<sr25519::Public>("Alice")),
const_on_chain_schema: vec![],
variable_on_chain_schema: vec![],
limits: CollectionLimits::default()
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -20,7 +20,7 @@
ensure, fail, parameter_types,
traits::{
Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,
- Randomness, IsSubType,
+ Randomness, IsSubType, WithdrawReasons,
},
weights::{
constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
@@ -28,6 +28,7 @@
WeightToFeePolynomial, DispatchClass,
},
StorageValue,
+ transactional,
};
use frame_system::{self as system, ensure_signed, ensure_root};
@@ -123,6 +124,42 @@
pub fraction: u128,
}
+#[derive(Encode, Decode, Debug, Clone, PartialEq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub enum SponsorshipState<AccountId> {
+ /// The fees are applied to the transaction sender
+ Disabled,
+ Unconfirmed(AccountId),
+ /// Transactions are sponsored by specified account
+ Confirmed(AccountId),
+}
+
+impl<AccountId> SponsorshipState<AccountId> {
+ fn sponsor(&self) -> Option<&AccountId> {
+ match self {
+ Self::Confirmed(sponsor) => Some(sponsor),
+ _ => None,
+ }
+ }
+
+ fn pending_sponsor(&self) -> Option<&AccountId> {
+ match self {
+ Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),
+ _ => None,
+ }
+ }
+
+ fn confirmed(&self) -> bool {
+ matches!(self, Self::Confirmed(_))
+ }
+}
+
+impl<T> Default for SponsorshipState<T> {
+ fn default() -> Self {
+ Self::Disabled
+ }
+}
+
#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct CollectionType<AccountId> {
@@ -136,8 +173,7 @@
pub mint_mode: bool,
pub offchain_schema: Vec<u8>,
pub schema_version: SchemaVersion,
- pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender
- pub sponsor_confirmed: bool, // False if sponsor address has not yet confirmed sponsorship. True otherwise.
+ pub sponsorship: SponsorshipState<AccountId>,
pub limits: CollectionLimits, // Collection private restrictions
pub variable_on_chain_schema: Vec<u8>, //
pub const_on_chain_schema: Vec<u8>, //
@@ -387,7 +423,9 @@
/// Schema data size limit bound exceeded
SchemaDataLimitExceeded,
/// Maximum refungibility exceeded
- WrongRefungiblePieces
+ WrongRefungiblePieces,
+ /// createRefungible should be called with one owner
+ BadCreateRefungibleCall,
}
}
@@ -396,6 +434,10 @@
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
+
+ type Currency: Currency<Self::AccountId>;
+ type CollectionCreationPrice: Get<<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance>;
+ type TreasuryAccountId: Get<Self::AccountId>;
}
#[cfg(feature = "runtime-benchmarks")]
@@ -403,54 +445,113 @@
// #endregion
+// # Used definitions
+//
+// ## User control levels
+//
+// chain-controlled - key is uncontrolled by user
+// i.e autoincrementing index
+// can use non-cryptographic hash
+// real - key is controlled by user
+// but it is hard to generate enough colliding values, i.e owner of signed txs
+// can use non-cryptographic hash
+// controlled - key is completly controlled by users
+// i.e maps with mutable keys
+// should use cryptographic hash
+//
+// ## User control level downgrade reasons
+//
+// ?1 - chain-controlled -> controlled
+// collections/tokens can be destroyed, resulting in massive holes
+// ?2 - chain-controlled -> controlled
+// same as ?1, but can be only added, resulting in easier exploitation
+// ?3 - real -> controlled
+// no confirmation required, so addresses can be easily generated
decl_storage! {
trait Store for Module<T: Config> as Nft {
- // Private members
- NextCollectionID: CollectionId;
+ //#region Private members
+ /// Id of next collection
CreatedCollectionCount: u32;
+ /// Used for migrations
ChainVersion: u64;
- ItemListIndex: map hasher(identity) CollectionId => TokenId;
+ /// Id of last collection token
+ /// Collection id (controlled?1)
+ ItemListIndex: map hasher(blake2_128_concat) CollectionId => TokenId;
+ //#endregion
- // Chain limits struct
+ //#region Chain limits struct
pub ChainLimit get(fn chain_limit) config(): ChainLimits;
+ //#endregion
- // Bound counters
- CollectionCount: u32;
+ //#region Bound counters
+ /// Amount of collections destroyed, used for total amount tracking with
+ /// CreatedCollectionCount
+ DestroyedCollectionCount: u32;
+ /// Total amount of account owned tokens (NFTs + RFTs + unique fungibles)
+ /// Account id (real)
pub AccountItemCount get(fn account_item_count): map hasher(twox_64_concat) T::AccountId => u32;
+ //#endregion
- // Basic collections
- pub Collection get(fn collection) config(): map hasher(identity) CollectionId => CollectionType<T::AccountId>;
- pub AdminList get(fn admin_list_collection): map hasher(identity) CollectionId => Vec<T::AccountId>;
- pub WhiteList get(fn white_list): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => bool;
+ //#region Basic collections
+ /// Collection info
+ /// Collection id (controlled?1)
+ pub Collection get(fn collection) config(): map hasher(blake2_128_concat) CollectionId => CollectionType<T::AccountId>;
+ /// List of collection admins
+ /// Collection id (controlled?2)
+ pub AdminList get(fn admin_list_collection): map hasher(blake2_128_concat) CollectionId => Vec<T::AccountId>;
+ /// Whitelisted collection users
+ /// Collection id (controlled?2), user id (controlled?3)
+ pub WhiteList get(fn white_list): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => bool;
+ //#endregion
- /// Balance owner per collection map
- pub Balance get(fn balance_count): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => u128;
+ /// How many of collection items user have
+ /// Collection id (controlled?2), account id (real)
+ pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => u128;
- /// second parameter: item id + owner account id + spender account id
- pub Allowances get(fn approved): double_map hasher(identity) CollectionId, hasher(twox_64_concat) (TokenId, T::AccountId, T::AccountId) => u128;
+ /// Amount of items which spender can transfer out of owners account (via transferFrom)
+ /// Collection id (controlled?2), (token id (controlled ?2) + owner account id (real) + spender account id (controlled?3))
+ pub Allowances get(fn approved): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) (TokenId, T::AccountId, T::AccountId) => u128;
- /// Item collections
- pub NftItemList get(fn nft_item_id) config(): double_map hasher(identity) CollectionId, hasher(identity) TokenId => NftItemType<T::AccountId>;
- pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => FungibleItemType;
- pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(identity) CollectionId, hasher(identity) TokenId => ReFungibleItemType<T::AccountId>;
+ //#region Item collections
+ /// Collection id (controlled?2), token id (controlled?1)
+ pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => NftItemType<T::AccountId>;
+ /// Collection id (controlled?2), owner (controlled?2)
+ pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => FungibleItemType;
+ /// Collection id (controlled?2), token id (controlled?1)
+ pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => ReFungibleItemType<T::AccountId>;
+ //#endregion
- /// Index list
- pub AddressTokens get(fn address_tokens): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => Vec<TokenId>;
+ //#region Index list
+ /// Collection id (controlled?2), tokens owner (controlled?2)
+ pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => Vec<TokenId>;
+ //#endregion
- /// Tokens transfer baskets
- pub CreateItemBasket get(fn create_item_basket): map hasher(twox_64_concat) (CollectionId, T::AccountId) => T::BlockNumber;
- pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(identity) CollectionId, hasher(identity) TokenId => T::BlockNumber;
- pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => T::BlockNumber;
- pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(identity) CollectionId, hasher(identity) TokenId => T::BlockNumber;
+ //#region Tokens transfer rate limit baskets
+ /// (Collection id (controlled?2), who created (real))
+ pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => T::BlockNumber;
+ /// Collection id (controlled?2), token id (controlled?2)
+ pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;
+ /// Collection id (controlled?2), owning user (real)
+ pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => T::BlockNumber;
+ /// Collection id (controlled?2), token id (controlled?2)
+ pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => T::BlockNumber;
+ //#endregion
- // Contract Sponsorship and Ownership
+ //#region Contract Sponsorship and Ownership
+ /// Contract address (real)
pub ContractOwner get(fn contract_owner): map hasher(twox_64_concat) T::AccountId => T::AccountId;
+ /// Contract address (real)
pub ContractSelfSponsoring get(fn contract_self_sponsoring): map hasher(twox_64_concat) T::AccountId => bool;
+ /// (Contract address(real), caller (real))
pub ContractSponsorBasket get(fn contract_sponsor_basket): map hasher(twox_64_concat) (T::AccountId, T::AccountId) => T::BlockNumber;
+ /// Contract address (real)
pub ContractSponsoringRateLimit get(fn contract_sponsoring_rate_limit): map hasher(twox_64_concat) T::AccountId => T::BlockNumber;
+ /// Contract address (real)
pub ContractWhiteListEnabled get(fn contract_white_list_enabled): map hasher(twox_64_concat) T::AccountId => bool;
- pub ContractWhiteList get(fn contract_white_list): double_map hasher(twox_64_concat) T::AccountId, hasher(twox_64_concat) T::AccountId => bool;
+ /// Contract address (real) => Whitelisted user (controlled?3)
+ pub ContractWhiteList get(fn contract_white_list): double_map hasher(twox_64_concat) T::AccountId, hasher(blake2_128_concat) T::AccountId => bool;
+ //#endregion
}
add_extra_genesis {
build(|config: &GenesisConfig<T>| {
@@ -534,14 +635,6 @@
type Error = Error<T>;
fn on_initialize(now: T::BlockNumber) -> Weight {
-
- if ChainVersion::get() < 2
- {
- let value = NextCollectionID::get();
- CreatedCollectionCount::put(value);
- ChainVersion::put(2);
- }
-
0
}
@@ -562,6 +655,7 @@
/// * mode: [CollectionMode] collection type and type dependent data.
// returns collection ID
#[weight = <T as Config>::WeightInfo::create_collection()]
+ #[transactional]
pub fn create_collection(origin,
collection_name: Vec<u16>,
collection_description: Vec<u16>,
@@ -571,6 +665,19 @@
// Anyone can create a collection
let who = ensure_signed(origin)?;
+ // Take a (non-refundable) deposit of collection creation
+ let mut imbalance = <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();
+ imbalance.subsume(<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(
+ &T::TreasuryAccountId::get(),
+ T::CollectionCreationPrice::get(),
+ ));
+ <T as Config>::Currency::settle(
+ &who,
+ imbalance,
+ WithdrawReasons::TRANSFER,
+ ExistenceRequirement::KeepAlive,
+ ).map_err(|_| Error::<T>::NoPermission)?;
+
let decimal_points = match mode {
CollectionMode::Fungible(points) => points,
_ => 0
@@ -578,8 +685,11 @@
let chain_limit = ChainLimit::get();
+ let created_count = CreatedCollectionCount::get();
+ let destroyed_count = DestroyedCollectionCount::get();
+
// bound Total number of collections
- ensure!(CollectionCount::get() < chain_limit.collection_numbers_limit, Error::<T>::TotalCollectionsLimitExceeded);
+ ensure!(created_count - destroyed_count < chain_limit.collection_numbers_limit, Error::<T>::TotalCollectionsLimitExceeded);
// check params
ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
@@ -588,17 +698,11 @@
ensure!(token_prefix.len() <= 16, Error::<T>::CollectionTokenPrefixLimitExceeded);
// Generate next collection ID
- let next_id = CreatedCollectionCount::get()
- .checked_add(1)
- .ok_or(Error::<T>::NumOverflow)?;
-
- // bound counter
- let total = CollectionCount::get()
+ let next_id = created_count
.checked_add(1)
.ok_or(Error::<T>::NumOverflow)?;
CreatedCollectionCount::put(next_id);
- CollectionCount::put(total);
let limits = CollectionLimits {
sponsored_data_size: chain_limit.custom_data_limit,
@@ -617,8 +721,7 @@
token_prefix: token_prefix,
offchain_schema: Vec::new(),
schema_version: SchemaVersion::ImageURL,
- sponsor: T::AccountId::default(),
- sponsor_confirmed: false,
+ sponsorship: SponsorshipState::Disabled,
variable_on_chain_schema: Vec::new(),
const_on_chain_schema: Vec::new(),
limits,
@@ -643,6 +746,7 @@
///
/// * collection_id: collection to destroy.
#[weight = <T as Config>::WeightInfo::destroy_collection()]
+ #[transactional]
pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {
let sender = ensure_signed(origin)?;
@@ -669,15 +773,9 @@
<FungibleTransferBasket<T>>::remove_prefix(collection_id);
<ReFungibleTransferBasket<T>>::remove_prefix(collection_id);
- if CollectionCount::get() > 0
- {
- // bound couter
- let total = CollectionCount::get()
- .checked_sub(1)
- .ok_or(Error::<T>::NumOverflow)?;
-
- CollectionCount::put(total);
- }
+ DestroyedCollectionCount::put(DestroyedCollectionCount::get()
+ .checked_add(1)
+ .ok_or(Error::<T>::NumOverflow)?);
Ok(())
}
@@ -695,6 +793,7 @@
///
/// * address.
#[weight = <T as Config>::WeightInfo::add_to_white_list()]
+ #[transactional]
pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{
let sender = ensure_signed(origin)?;
@@ -718,6 +817,7 @@
///
/// * address.
#[weight = <T as Config>::WeightInfo::remove_from_white_list()]
+ #[transactional]
pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{
let sender = ensure_signed(origin)?;
@@ -740,6 +840,7 @@
///
/// * mode: [AccessMode]
#[weight = <T as Config>::WeightInfo::set_public_access_mode()]
+ #[transactional]
pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult
{
let sender = ensure_signed(origin)?;
@@ -766,6 +867,7 @@
///
/// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.
#[weight = <T as Config>::WeightInfo::set_mint_permission()]
+ #[transactional]
pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult
{
let sender = ensure_signed(origin)?;
@@ -790,6 +892,7 @@
///
/// * new_owner.
#[weight = <T as Config>::WeightInfo::change_collection_owner()]
+ #[transactional]
pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {
let sender = ensure_signed(origin)?;
@@ -815,6 +918,7 @@
///
/// * new_admin_id: Address of new admin to add.
#[weight = <T as Config>::WeightInfo::add_collection_admin()]
+ #[transactional]
pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::AccountId) -> DispatchResult {
let sender = ensure_signed(origin)?;
@@ -849,6 +953,7 @@
///
/// * account_id: Address of admin to remove.
#[weight = <T as Config>::WeightInfo::remove_collection_admin()]
+ #[transactional]
pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::AccountId) -> DispatchResult {
let sender = ensure_signed(origin)?;
@@ -872,6 +977,7 @@
///
/// * new_sponsor.
#[weight = <T as Config>::WeightInfo::set_collection_sponsor()]
+ #[transactional]
pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {
let sender = ensure_signed(origin)?;
@@ -880,8 +986,7 @@
let mut target_collection = <Collection<T>>::get(collection_id);
ensure!(sender == target_collection.owner, Error::<T>::NoPermission);
- target_collection.sponsor = new_sponsor;
- target_collection.sponsor_confirmed = false;
+ target_collection.sponsorship = SponsorshipState::Unconfirmed(new_sponsor);
<Collection<T>>::insert(collection_id, target_collection);
Ok(())
@@ -895,15 +1000,19 @@
///
/// * collection_id.
#[weight = <T as Config>::WeightInfo::confirm_sponsorship()]
+ #[transactional]
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);
- ensure!(sender == target_collection.sponsor, Error::<T>::ConfirmUnsetSponsorFail);
+ ensure!(
+ target_collection.sponsorship.pending_sponsor() == Some(&sender),
+ Error::<T>::ConfirmUnsetSponsorFail
+ );
- target_collection.sponsor_confirmed = true;
+ target_collection.sponsorship = SponsorshipState::Confirmed(sender);
<Collection<T>>::insert(collection_id, target_collection);
Ok(())
@@ -919,6 +1028,7 @@
///
/// * collection_id.
#[weight = <T as Config>::WeightInfo::remove_collection_sponsor()]
+ #[transactional]
pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {
let sender = ensure_signed(origin)?;
@@ -927,8 +1037,7 @@
let mut target_collection = <Collection<T>>::get(collection_id);
ensure!(sender == target_collection.owner, Error::<T>::NoPermission);
- target_collection.sponsor = T::AccountId::default();
- target_collection.sponsor_confirmed = false;
+ target_collection.sponsorship = SponsorshipState::Disabled;
<Collection<T>>::insert(collection_id, target_collection);
Ok(())
@@ -959,6 +1068,7 @@
// .saturating_add(RocksDbWeight::get().writes(8 as Weight))]
#[weight = <T as Config>::WeightInfo::create_item(data.len())]
+ #[transactional]
pub fn create_item(origin, collection_id: CollectionId, owner: T::AccountId, data: CreateItemData) -> DispatchResult {
let sender = ensure_signed(origin)?;
@@ -974,7 +1084,7 @@
Ok(())
}
- /// This method creates multiple instances of NFT Collection created with CreateCollection method.
+ /// This method creates multiple items in a collection created with CreateCollection method.
///
/// # Permissions
///
@@ -995,6 +1105,7 @@
#[weight = <T as Config>::WeightInfo::create_item(items_data.into_iter()
.map(|data| { data.len() })
.sum())]
+ #[transactional]
pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::AccountId, items_data: Vec<CreateItemData>) -> DispatchResult {
ensure!(items_data.len() > 0, Error::<T>::EmptyArgument);
@@ -1029,6 +1140,7 @@
///
/// * item_id: ID of NFT to burn.
#[weight = <T as Config>::WeightInfo::burn_item()]
+ #[transactional]
pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {
let sender = ensure_signed(origin)?;
@@ -1087,6 +1199,7 @@
/// * Fungible Mode: Must specify transferred amount
/// * Re-Fungible Mode: Must specify transferred portion (between 0 and 1)
#[weight = <T as Config>::WeightInfo::transfer()]
+ #[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)
@@ -1108,6 +1221,7 @@
///
/// * item_id: ID of the item.
#[weight = <T as Config>::WeightInfo::approve()]
+ #[transactional]
pub fn approve(origin, spender: T::AccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {
let sender = ensure_signed(origin)?;
@@ -1171,6 +1285,7 @@
///
/// * value: Amount to transfer.
#[weight = <T as Config>::WeightInfo::transfer_from()]
+ #[transactional]
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)?;
@@ -1205,7 +1320,7 @@
}
// Reduce approval by transferred amount or remove if remaining approval drops to 0
- if approval.checked_sub(value).unwrap_or(0) > 0 {
+ if approval.saturating_sub(value) > 0 {
<Allowances<T>>::insert(collection_id, (item_id, &from, &sender), approval - value);
}
else {
@@ -1251,6 +1366,7 @@
///
/// * schema: String representing the offchain data schema.
#[weight = <T as Config>::WeightInfo::set_variable_meta_data()]
+ #[transactional]
pub fn set_variable_meta_data (
origin,
collection_id: CollectionId,
@@ -1296,6 +1412,7 @@
///
/// * schema: SchemaVersion: enum
#[weight = <T as Config>::WeightInfo::set_schema_version()]
+ #[transactional]
pub fn set_schema_version(
origin,
collection_id: CollectionId,
@@ -1323,6 +1440,7 @@
///
/// * schema: String representing the offchain data schema.
#[weight = <T as Config>::WeightInfo::set_offchain_schema()]
+ #[transactional]
pub fn set_offchain_schema(
origin,
collection_id: CollectionId,
@@ -1354,6 +1472,7 @@
///
/// * schema: String representing the const on-chain data schema.
#[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]
+ #[transactional]
pub fn set_const_on_chain_schema (
origin,
collection_id: CollectionId,
@@ -1385,6 +1504,7 @@
///
/// * schema: String representing the variable on-chain data schema.
#[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]
+ #[transactional]
pub fn set_variable_on_chain_schema (
origin,
collection_id: CollectionId,
@@ -1405,6 +1525,7 @@
// Sudo permissions function
#[weight = <T as Config>::WeightInfo::set_chain_limits()]
+ #[transactional]
pub fn set_chain_limits(
origin,
limits: ChainLimits
@@ -1429,6 +1550,7 @@
/// * enable flag
///
#[weight = <T as Config>::WeightInfo::enable_contract_sponsoring()]
+ #[transactional]
pub fn enable_contract_sponsoring(
origin,
contract_address: T::AccountId,
@@ -1464,6 +1586,7 @@
/// -`rate_limit`: Number of blocks to wait until the next sponsored transaction is allowed
///
#[weight = <T as Config>::WeightInfo::set_contract_sponsoring_rate_limit()]
+ #[transactional]
pub fn set_contract_sponsoring_rate_limit(
origin,
contract_address: T::AccountId,
@@ -1491,6 +1614,7 @@
///
/// - `enable`: .
#[weight = <T as Config>::WeightInfo::toggle_contract_white_list()]
+ #[transactional]
pub fn toggle_contract_white_list(
origin,
contract_address: T::AccountId,
@@ -1518,6 +1642,7 @@
///
/// -`account_address`: Address to add.
#[weight = <T as Config>::WeightInfo::add_to_contract_white_list()]
+ #[transactional]
pub fn add_to_contract_white_list(
origin,
contract_address: T::AccountId,
@@ -1545,6 +1670,7 @@
///
/// -`account_address`: Address to remove.
#[weight = <T as Config>::WeightInfo::remove_from_contract_white_list()]
+ #[transactional]
pub fn remove_from_contract_white_list(
origin,
contract_address: T::AccountId,
@@ -1561,6 +1687,7 @@
}
#[weight = <T as Config>::WeightInfo::set_collection_limits()]
+ #[transactional]
pub fn set_collection_limits(
origin,
collection_id: u32,
@@ -1726,9 +1853,6 @@
}
};
- // call event
- Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id), owner));
-
Ok(())
}
@@ -1752,6 +1876,7 @@
.ok_or(Error::<T>::NumOverflow)?;
<Balance<T>>::insert(collection_id, (*owner).clone(), new_balance);
+ Self::deposit_event(RawEvent::ItemCreated(collection_id, 0, owner.clone()));
Ok(())
}
@@ -1761,8 +1886,14 @@
.ok_or(Error::<T>::NumOverflow)?;
let itemcopy = item.clone();
- let value = item.owner.first().unwrap().fraction;
- let owner = item.owner.first().unwrap().owner.clone();
+ ensure!(
+ item.owner.len() == 1,
+ Error::<T>::BadCreateRefungibleCall,
+ );
+ let item_owner = item.owner.first().expect("only one owner is defined");
+
+ let value = item_owner.fraction;
+ let owner = item_owner.owner.clone();
Self::add_token_index(collection_id, current_index, &owner)?;
@@ -1775,6 +1906,7 @@
.ok_or(Error::<T>::NumOverflow)?;
<Balance<T>>::insert(collection_id, owner.clone(), new_balance);
+ Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, owner));
Ok(())
}
@@ -1795,6 +1927,7 @@
.ok_or(Error::<T>::NumOverflow)?;
<Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);
+ Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, item_owner));
Ok(())
}
@@ -1811,9 +1944,8 @@
let rft_balance = token
.owner
.iter()
- .filter(|&i| i.owner == *owner)
- .next()
- .unwrap();
+ .find(|&i| i.owner == *owner)
+ .ok_or(Error::<T>::TokenNotFound)?;
Self::remove_token_index(collection_id, item_id, owner)?;
// update balance
@@ -1827,7 +1959,7 @@
.owner
.iter()
.position(|i| i.owner == *owner)
- .unwrap();
+ .expect("owned item is exists");
token.owner.remove(index);
let owner_count = token.owner.len();
@@ -2054,7 +2186,7 @@
.iter()
.filter(|i| i.owner == owner)
.next()
- .ok_or(Error::<T>::NumOverflow)?;
+ .ok_or(Error::<T>::TokenNotFound)?;
let amount = item.fraction;
ensure!(amount >= value, Error::<T>::TokenValueTooLow);
@@ -2065,10 +2197,10 @@
.ok_or(Error::<T>::NumOverflow)?;
<Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);
- let balancenew_owner = <Balance<T>>::get(collection_id, new_owner.clone())
+ let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())
.checked_add(value)
.ok_or(Error::<T>::NumOverflow)?;
- <Balance<T>>::insert(collection_id, new_owner.clone(), balancenew_owner);
+ <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);
let old_owner = item.owner.clone();
let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);
@@ -2082,7 +2214,7 @@
.owner
.iter_mut()
.find(|i| i.owner == owner)
- .unwrap()
+ .expect("old owner does present in refungible")
.owner = new_owner.clone();
<ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);
@@ -2094,7 +2226,7 @@
.owner
.iter_mut()
.find(|i| i.owner == owner)
- .unwrap()
+ .expect("old owner does present in refungible")
.fraction -= value;
// separate amount
@@ -2104,7 +2236,7 @@
.owner
.iter_mut()
.find(|i| i.owner == new_owner)
- .unwrap()
+ .expect("new owner has account")
.fraction += value;
} else {
// new owner do not have account
@@ -2424,13 +2556,6 @@
> {
let tip = self.0;
- // Set fee based on call type. Creating collection costs 1 Unique.
- // All other transactions have traditional fees so far
- // let fee = match call.is_sub_type() {
- // Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),
- // _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes
- // // _ => <BalanceOf<T>>::from(100)
- // };
let fee = Self::traditional_fee(len, info, tip);
// Only mess with balances if fee is not zero.
@@ -2447,7 +2572,9 @@
// sponsor timeout
let block_number = <system::Module<T>>::block_number() as T::BlockNumber;
- let limit = <Collection<T>>::get(collection_id).limits.sponsor_transfer_timeout;
+ let collection = <Collection<T>>::get(collection_id);
+
+ let limit = collection.limits.sponsor_transfer_timeout;
let mut sponsored = true;
if <CreateItemBasket<T>>::contains_key((collection_id, &who)) {
let last_tx_block = <CreateItemBasket<T>>::get((collection_id, &who));
@@ -2461,11 +2588,12 @@
}
// check free create limit
- if (<Collection<T>>::get(collection_id).limits.sponsored_data_size >= (_properties.len() as u32)) &&
- (<Collection<T>>::get(collection_id).sponsor_confirmed) &&
+ if (collection.limits.sponsored_data_size >= (_properties.len() as u32)) &&
(sponsored)
{
- <Collection<T>>::get(collection_id).sponsor
+ collection.sponsorship.sponsor()
+ .cloned()
+ .unwrap_or_default()
} else {
T::AccountId::default()
}
@@ -2473,7 +2601,7 @@
Some(Call::transfer(_new_owner, collection_id, item_id, _value)) => {
let mut sponsor_transfer = false;
- if <Collection<T>>::get(collection_id).sponsor_confirmed {
+ if <Collection<T>>::get(collection_id).sponsorship.confirmed() {
let collection_limits = <Collection<T>>::get(collection_id).limits;
let collection_mode = <Collection<T>>::get(collection_id).mode;
@@ -2560,7 +2688,9 @@
if !sponsor_transfer {
T::AccountId::default()
} else {
- <Collection<T>>::get(collection_id).sponsor
+ <Collection<T>>::get(collection_id).sponsorship.sponsor()
+ .cloned()
+ .unwrap_or_default()
}
}
pallets/nft/src/mock.rsdiffbeforeafterboth--- a/pallets/nft/src/mock.rs
+++ b/pallets/nft/src/mock.rs
@@ -1,43 +1,44 @@
-// Creating mock runtime here
-
-use crate::{Module, Config};
-
-use frame_support::{
- impl_outer_origin, parameter_types,
- weights::{Weight, IdentityFee},
+use crate as pallet_template;
+use sp_core::H256;
+use frame_support::{
+ parameter_types,
+ weights::IdentityFee,
};
-use frame_system as system;
-use system::limits::{BlockLength, BlockWeights};
-use transaction_payment::{self, CurrencyAdapter};
-use sp_core::H256;
use sp_runtime::{
- testing::Header,
- traits::{BlakeTwo256, IdentityLookup},
- Perbill,
+ traits::{BlakeTwo256, IdentityLookup},
+ testing::Header,
+ Perbill,
};
-use pallet_contracts::WeightInfo;
-pub use pallet_balances;
+use pallet_transaction_payment::{ CurrencyAdapter};
+use frame_system as system;
-impl_outer_origin! {
- pub enum Origin for Test {}
-}
+type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
+type Block = frame_system::mocking::MockBlock<Test>;
-// For testing the pallet, we construct most of a mock runtime. This means
-// first constructing a configuration type (`Test`) which `impl`s each of the
-// configuration traits of pallets we want to use.
-#[derive(Clone, Eq, PartialEq)]
-pub struct Test;
+// Configure a mock runtime to test the pallet.
+frame_support::construct_runtime!(
+ pub enum Test where
+ Block = Block,
+ NodeBlock = Block,
+ UncheckedExtrinsic = UncheckedExtrinsic,
+ {
+ System: frame_system::{Module, Call, Config, Storage, Event<T>},
+ TemplateModule: pallet_template::{Module, Call, Storage},
+ }
+);
+
parameter_types! {
- pub const BlockHashCount: u64 = 250;
- pub TestBlockWeights: BlockWeights = BlockWeights::default();
- pub TestBlockLength: BlockLength = BlockLength::default();
- pub SS58Prefix: u8 = 0;
+ pub const BlockHashCount: u64 = 250;
+ pub const SS58Prefix: u8 = 42;
}
impl system::Config for Test {
type BaseCallFilter = ();
+ type BlockWeights = ();
+ type BlockLength = ();
+ type DbWeight = ();
type Origin = Origin;
- type Call = ();
+ type Call = Call;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
@@ -47,24 +48,20 @@
type Header = Header;
type Event = ();
type BlockHashCount = BlockHashCount;
- type BlockWeights = TestBlockWeights;
- type DbWeight = ();
- type BlockLength = TestBlockLength;
type Version = ();
- type PalletInfo = ();
+ type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<u64>;
type OnNewAccount = ();
type OnKilledAccount = ();
+ type SystemWeightInfo = ();
type SS58Prefix = SS58Prefix;
- type SystemWeightInfo = ();
}
parameter_types! {
pub const ExistentialDeposit: u64 = 1;
pub const MaxLocks: u32 = 50;
}
-
-type System = frame_system::Module<Test>;
+//frame_system::Module<Test>;
impl pallet_balances::Config for Test {
type AccountStore = System;
type Balance = u64;
@@ -79,13 +76,12 @@
pub const TransactionByteFee: u64 = 1;
}
-impl transaction_payment::Config for Test {
+impl pallet_transaction_payment::Config for Test {
type OnChargeTransaction = CurrencyAdapter<pallet_balances::Module<Test>, ()>;
type TransactionByteFee = TransactionByteFee;
type WeightToFee = IdentityFee<u64>;
type FeeMultiplierUpdate = ();
}
-
parameter_types! {
pub const MinimumPeriod: u64 = 1;
@@ -110,12 +106,8 @@
pub const SignedClaimHandicap: u32 = 2;
pub const MaxDepth: u32 = 32;
pub const MaxValueSize: u32 = 16 * 1024;
- pub DeletionWeightLimit: Weight = Perbill::from_percent(10) *
- TestBlockWeights::get().max_block;
- pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (
- <Test as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -
- <Test as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)
- )) / 5) as u32;
+ pub DeletionWeightLimit: u64 = u64::MAX;//Perbill::from_percent(10);
+ pub DeletionQueueDepth: u32 = 10;
}
impl pallet_contracts::Config for Test {
@@ -136,23 +128,22 @@
type DeletionQueueDepth = DeletionQueueDepth;
type MaxValueSize = MaxValueSize;
type ChainExtension = ();
+ type MaxCodeSize = ();
type WeightPrice = ();
type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;
}
-impl Config for Test {
+parameter_types! {
+ pub const CollectionCreationPrice: u64 = 1_000_000_000_000;
+}
+
+impl pallet_template::Config for Test {
type Event = ();
type WeightInfo = ();
-
+ type CollectionCreationPrice = CollectionCreationPrice;
}
-pub type TemplateModule = Module<Test>;
-
-// This function basically just builds a genesis storage key/value store according to
-// our desired mockup.
+// Build genesis storage according to the mock runtime.
pub fn new_test_ext() -> sp_io::TestExternalities {
- system::GenesisConfig::default()
- .build_storage::<Test>()
- .unwrap()
- .into()
-}
+ system::GenesisConfig::default().build_storage::<Test>().unwrap().into()
+}
\ No newline at end of file
runtime/src/lib.rsdiffbeforeafterboth--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -24,7 +24,7 @@
create_runtime_str, generic, impl_opaque_keys,
traits::{
Convert, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount,
- IdentityLookup, NumberFor, Verify,
+ IdentityLookup, NumberFor, Verify, AccountIdConversion,
},
transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult, MultiSignature,
@@ -520,10 +520,18 @@
type WeightInfo = ();
}
+parameter_types! {
+ pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();
+ pub const CollectionCreationPrice: Balance = 100 * UNIQUE;
+}
+
/// Used for the module nft in `./nft.rs`
impl pallet_nft::Config for Runtime {
type Event = Event;
type WeightInfo = nft_weights::WeightInfo;
+ type Currency = Balances;
+ type CollectionCreationPrice = CollectionCreationPrice;
+ type TreasuryAccountId = TreasuryAccountId;
}
construct_runtime!(
runtime_types.jsondiffbeforeafterboth--- a/runtime_types.json
+++ b/runtime_types.json
@@ -31,6 +31,13 @@
"ConstData": "Vec<u8>",
"VariableData": "Vec<u8>"
},
+ "SponsorshipState": {
+ "_enum": {
+ "Disabled": null,
+ "Unconfirmed": "AccountId",
+ "Confirmed": "AccountId"
+ }
+ },
"CollectionType": {
"Owner": "AccountId",
"Mode": "CollectionMode",
@@ -42,8 +49,7 @@
"MintMode": "bool",
"OffchainSchema": "Vec<u8>",
"SchemaVersion": "SchemaVersion",
- "Sponsor": "AccountId",
- "SponsorConfirmed": "bool",
+ "Sponsorship": "SponsorshipState",
"Limits": "CollectionLimits",
"VariableOnChainSchema": "Vec<u8>",
"ConstOnChainSchema": "Vec<u8>"
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -25,7 +25,10 @@
"testSetSchemaVersion": "mocha --timeout 9999999 -r ts-node/register ./**/setSchemaVersion.test.ts",
"testSetVariableMetaData": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetaData.test.ts",
"testSetCollectionLimits": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionLimits.test.ts",
+ "testSetCollectionSponsor": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionSponsor.test.ts",
+ "testConfirmSponsorship": "mocha --timeout 9999999 -r ts-node/register ./**/confirmSponsorship.test.ts",
"testRemoveCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionAdmin.test.ts",
+ "testRemoveCollectionSponsor": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionSponsor.test.ts",
"testRemoveFromWhiteList": "mocha --timeout 9999999 -r ts-node/register ./**/removeFromWhiteList.test.ts",
"testConnection": "mocha --timeout 9999999 -r ts-node/register ./**/connection.test.ts",
"testCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts",
tests/src/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -1,59 +1,59 @@
-//
-// This file is subject to the terms and conditions defined in
-// file 'LICENSE', which is part of this source code package.
-//
-
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import { default as usingApi } from './substrate/substrate-api';
-import { createCollectionExpectFailure, createCollectionExpectSuccess } from './util/helpers';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
-
-describe('integration test: ext. createCollection():', () => {
- it('Create new NFT collection', async () => {
- await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
- });
- it('Create new NFT collection whith collection_name of maximum length (64 bytes)', async () => {
- await createCollectionExpectSuccess({name: 'A'.repeat(64)});
- });
- it('Create new NFT collection whith collection_description of maximum length (256 bytes)', async () => {
- await createCollectionExpectSuccess({description: 'A'.repeat(256)});
- });
- it('Create new NFT collection whith token_prefix of maximum length (16 bytes)', async () => {
- await createCollectionExpectSuccess({tokenPrefix: 'A'.repeat(16)});
- });
- it('Create new Fungible collection', async () => {
- await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
- });
- it('Create new ReFungible collection', async () => {
- await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- });
-});
-
-describe('(!negative test!) integration test: ext. createCollection():', () => {
- it('(!negative test!) create new NFT collection whith incorrect data (mode)', async () => {
- await usingApi(async (api) => {
- const AcollectionCount = parseInt((await api.query.nft.collectionCount()).toString(), 10);
-
- const badTransaction = async () => {
- await createCollectionExpectSuccess({mode: {type: 'Invalid'}});
- };
- // tslint:disable-next-line:no-unused-expression
- expect(badTransaction()).to.be.rejected;
-
- const BcollectionCount = parseInt((await api.query.nft.collectionCount()).toString(), 10);
- expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Incorrect collection created.');
- });
- });
- it('(!negative test!) create new NFT collection whith incorrect data (collection_name)', async () => {
- await createCollectionExpectFailure({ name: 'A'.repeat(65), mode: {type: 'NFT'}});
- });
- it('(!negative test!) create new NFT collection whith incorrect data (collection_description)', async () => {
- await createCollectionExpectFailure({ description: 'A'.repeat(257), mode: { type: 'NFT' }});
- });
- it('(!negative test!) create new NFT collection whith incorrect data (token_prefix)', async () => {
- await createCollectionExpectFailure({tokenPrefix: 'A'.repeat(17), mode: {type: 'NFT'}});
- });
-});
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import { default as usingApi } from './substrate/substrate-api';
+import { createCollectionExpectFailure, createCollectionExpectSuccess } from './util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+describe('integration test: ext. createCollection():', () => {
+ it('Create new NFT collection', async () => {
+ await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
+ });
+ it('Create new NFT collection whith collection_name of maximum length (64 bytes)', async () => {
+ await createCollectionExpectSuccess({name: 'A'.repeat(64)});
+ });
+ it('Create new NFT collection whith collection_description of maximum length (256 bytes)', async () => {
+ await createCollectionExpectSuccess({description: 'A'.repeat(256)});
+ });
+ it('Create new NFT collection whith token_prefix of maximum length (16 bytes)', async () => {
+ await createCollectionExpectSuccess({tokenPrefix: 'A'.repeat(16)});
+ });
+ it('Create new Fungible collection', async () => {
+ await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+ });
+ it('Create new ReFungible collection', async () => {
+ await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+ });
+});
+
+describe('(!negative test!) integration test: ext. createCollection():', () => {
+ it('(!negative test!) create new NFT collection whith incorrect data (mode)', async () => {
+ await usingApi(async (api) => {
+ const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);
+
+ const badTransaction = async () => {
+ await createCollectionExpectSuccess({mode: {type: 'Invalid'}});
+ };
+ // tslint:disable-next-line:no-unused-expression
+ expect(badTransaction()).to.be.rejected;
+
+ const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);
+ expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Incorrect collection created.');
+ });
+ });
+ it('(!negative test!) create new NFT collection whith incorrect data (collection_name)', async () => {
+ await createCollectionExpectFailure({ name: 'A'.repeat(65), mode: {type: 'NFT'}});
+ });
+ it('(!negative test!) create new NFT collection whith incorrect data (collection_description)', async () => {
+ await createCollectionExpectFailure({ description: 'A'.repeat(257), mode: { type: 'NFT' }});
+ });
+ it('(!negative test!) create new NFT collection whith incorrect data (token_prefix)', async () => {
+ await createCollectionExpectFailure({tokenPrefix: 'A'.repeat(17), mode: {type: 'NFT'}});
+ });
+});
tests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth--- a/tests/src/creditFeesToTreasury.test.ts
+++ b/tests/src/creditFeesToTreasury.test.ts
@@ -25,6 +25,7 @@
const Treasury = "5EYCAe5ijiYfyeZ2JJCGq56LmPyNRAKzpG4QkoQkkQNB5e6Z";
const saneMinimumFee = 0.05;
const saneMaximumFee = 0.5;
+const createCollectionDeposit = 100;
let alice: IKeyringPair;
let bob: IKeyringPair;
@@ -127,8 +128,8 @@
const aliceBalanceAfter = new BigNumber((await api.query.system.account(alicesPublicKey)).data.free.toString());
const fee = aliceBalanceBefore.minus(aliceBalanceAfter);
- expect(fee.dividedBy(1e15).toNumber()).to.be.lessThan(saneMaximumFee);
- expect(fee.dividedBy(1e15).toNumber()).to.be.greaterThan(saneMinimumFee);
+ expect(fee.dividedBy(1e15).toNumber()).to.be.lessThan(saneMaximumFee + createCollectionDeposit);
+ expect(fee.dividedBy(1e15).toNumber()).to.be.greaterThan(saneMinimumFee + createCollectionDeposit);
});
});
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.Sponsor.toString()).to.be.equal(sponsor.toString());381 expect(collection.SponsorConfirmed).to.be.false;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.collection(collectionId)).toJSON();396397 // What to expect398 expect(result.success).to.be.true;399 expect(collection.Sponsor).to.be.equal(nullPublicKey);400 expect(collection.SponsorConfirmed).to.be.false;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.Sponsor).to.be.equal(sender.address);439 expect(collection.SponsorConfirmed).to.be.true;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.collection(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.collection(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.collection(collectionId) 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.collection(collectionId)) as unknown as ICollectionInterface;960 });961}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.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}