difftreelog
refactor use rpcs instead of api.query.common
in: master
33 files changed
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -3,7 +3,7 @@
use codec::Decode;
use jsonrpc_core::{Error as RpcError, ErrorCode, Result};
use jsonrpc_derive::rpc;
-use nft_data_structs::{CollectionId, TokenId};
+use nft_data_structs::{Collection, CollectionId, CollectionStats, TokenId};
use sp_api::{BlockId, BlockT, ProvideRuntimeApi};
use sp_blockchain::HeaderBackend;
use up_rpc::NftApi as NftRuntimeApi;
@@ -86,8 +86,23 @@
collection: CollectionId,
at: Option<BlockHash>,
) -> Result<Vec<CrossAccountId>>;
+ #[rpc(name = "nft_allowed")]
+ fn allowed(
+ &self,
+ collection: CollectionId,
+ user: CrossAccountId,
+ at: Option<BlockHash>,
+ ) -> Result<bool>;
#[rpc(name = "nft_lastTokenId")]
fn last_token_id(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<TokenId>;
+ #[rpc(name = "nft_collectionById")]
+ fn collection_by_id(
+ &self,
+ collection: CollectionId,
+ at: Option<BlockHash>,
+ ) -> Result<Option<Collection<AccountId>>>;
+ #[rpc(name = "nft_collectionStats")]
+ fn collection_stats(&self, at: Option<BlockHash>) -> Result<CollectionStats>;
}
pub struct Nft<C, P> {
@@ -160,5 +175,8 @@
pass_method!(adminlist(collection: CollectionId) -> Vec<CrossAccountId>);
pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>);
+ pass_method!(allowed(collection: CollectionId, user: CrossAccountId) -> bool);
pass_method!(last_token_id(collection: CollectionId) -> TokenId);
+ pass_method!(collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>>);
+ pass_method!(collection_stats() -> CollectionStats);
}
pallets/common/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -19,7 +19,7 @@
pub fn create_collection_raw<T: Config, R>(
owner: T::AccountId,
mode: CollectionMode,
- handler: impl FnOnce(Collection<T>) -> Result<CollectionId, DispatchError>,
+ handler: impl FnOnce(Collection<T::AccountId>) -> Result<CollectionId, DispatchError>,
cast: impl FnOnce(CollectionHandle<T>) -> R,
) -> Result<R, DispatchError> {
T::Currency::deposit_creating(&owner, T::CollectionCreationPrice::get());
pallets/common/src/lib.rsdiffbeforeafterboth1#![cfg_attr(not(feature = "std"), no_std)]23use core::ops::{Deref, DerefMut};4use sp_std::vec::Vec;5use account::CrossAccountId;6use frame_support::{7 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo},8 ensure, fail,9 traits::{Imbalance, Get, Currency},10};11use nft_data_structs::{12 COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,13 MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_COLLECTION_NAME_LENGTH, MAX_TOKEN_PREFIX_LENGTH,14 COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo, TokenId, Weight,15 WithdrawReasons,16};17pub use pallet::*;18use sp_core::H160;19use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};20pub mod account;21#[cfg(feature = "runtime-benchmarks")]22pub mod benchmarking;23pub mod erc;24pub mod eth;2526#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]27pub struct CollectionHandle<T: Config> {28 pub id: CollectionId,29 collection: Collection<T>,30 pub recorder: pallet_evm_coder_substrate::SubstrateRecorder<T>,31}32impl<T: Config> CollectionHandle<T> {33 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {34 <CollectionById<T>>::get(id).map(|collection| Self {35 id,36 collection,37 recorder: pallet_evm_coder_substrate::SubstrateRecorder::new(38 eth::collection_id_to_address(id),39 gas_limit,40 ),41 })42 }43 pub fn new(id: CollectionId) -> Option<Self> {44 Self::new_with_gas_limit(id, u64::MAX)45 }46 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {47 Ok(Self::new(id).ok_or_else(|| <Error<T>>::CollectionNotFound)?)48 }49 pub fn log(&self, log: impl evm_coder::ToLog) -> DispatchResult {50 self.recorder.log_sub(log)51 }52 pub fn log_infallible(&self, log: impl evm_coder::ToLog) {53 self.recorder.log_infallible(log)54 }55 #[allow(dead_code)]56 fn consume_gas(&self, gas: u64) -> DispatchResult {57 self.recorder.consume_gas_sub(gas)58 }59 pub fn consume_sload(&self) -> DispatchResult {60 self.recorder.consume_sload_sub()61 }62 pub fn consume_sstores(&self, amount: usize) -> DispatchResult {63 self.recorder.consume_sstores_sub(amount)64 }65 pub fn consume_sstore(&self) -> DispatchResult {66 self.recorder.consume_sstore_sub()67 }68 pub fn consume_log(&self, topics: usize, data: usize) -> DispatchResult {69 self.recorder.consume_log_sub(topics, data)70 }71 pub fn submit_logs(self) -> DispatchResult {72 self.recorder.submit_logs()73 }74 pub fn save(self) -> DispatchResult {75 self.recorder.submit_logs()?;76 <CollectionById<T>>::insert(self.id, self.collection);77 Ok(())78 }79}80impl<T: Config> Deref for CollectionHandle<T> {81 type Target = Collection<T>;8283 fn deref(&self) -> &Self::Target {84 &self.collection85 }86}8788impl<T: Config> DerefMut for CollectionHandle<T> {89 fn deref_mut(&mut self) -> &mut Self::Target {90 &mut self.collection91 }92}9394impl<T: Config> CollectionHandle<T> {95 pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {96 ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);97 Ok(())98 }99 pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> Result<bool, DispatchError> {100 self.consume_sload()?;101102 Ok(*subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject)))103 }104 pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {105 ensure!(self.is_owner_or_admin(subject)?, <Error<T>>::NoPermission);106 Ok(())107 }108 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> Result<bool, DispatchError> {109 Ok(self.limits.owner_can_transfer() && self.is_owner_or_admin(user)?)110 }111 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> Result<bool, DispatchError> {112 Ok(self.limits.owner_can_transfer() && self.is_owner_or_admin(user)?)113 }114 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {115 self.consume_sload()?;116117 ensure!(118 <Allowlist<T>>::get((self.id, user)),119 <Error<T>>::AddressNotInAllowlist120 );121 Ok(())122 }123124 pub fn check_can_update_meta(125 &self,126 subject: &T::CrossAccountId,127 item_owner: &T::CrossAccountId,128 ) -> DispatchResult {129 match self.meta_update_permission {130 MetaUpdatePermission::ItemOwner => {131 ensure!(subject == item_owner, <Error<T>>::NoPermission);132 Ok(())133 }134 MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),135 MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),136 }137 }138}139140#[frame_support::pallet]141pub mod pallet {142 use super::*;143 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key};144 use account::{EvmBackwardsAddressMapping, CrossAccountId};145 use frame_support::traits::Currency;146 use nft_data_structs::TokenId;147 use scale_info::TypeInfo;148149 #[pallet::config]150 pub trait Config: frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo {151 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;152153 type CrossAccountId: CrossAccountId<Self::AccountId>;154155 type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;156 type EvmBackwardsAddressMapping: EvmBackwardsAddressMapping<Self::AccountId>;157158 type Currency: Currency<Self::AccountId>;159 type CollectionCreationPrice: Get<160 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,161 >;162 type TreasuryAccountId: Get<Self::AccountId>;163 }164165 #[pallet::pallet]166 #[pallet::generate_store(pub(super) trait Store)]167 pub struct Pallet<T>(_);168169 #[pallet::extra_constants]170 impl<T: Config> Pallet<T> {171 pub fn collection_admins_limit() -> u32 {172 COLLECTION_ADMINS_LIMIT173 }174 }175176 #[pallet::event]177 #[pallet::generate_deposit(pub fn deposit_event)]178 pub enum Event<T: Config> {179 /// New collection was created180 ///181 /// # Arguments182 ///183 /// * collection_id: Globally unique identifier of newly created collection.184 ///185 /// * mode: [CollectionMode] converted into u8.186 ///187 /// * account_id: Collection owner.188 CollectionCreated(CollectionId, u8, T::AccountId),189190 /// New item was created.191 ///192 /// # Arguments193 ///194 /// * collection_id: Id of the collection where item was created.195 ///196 /// * item_id: Id of an item. Unique within the collection.197 ///198 /// * recipient: Owner of newly created item199 ///200 /// * amount: Always 1 for NFT201 ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),202203 /// Collection item was burned.204 ///205 /// # Arguments206 ///207 /// * collection_id.208 ///209 /// * item_id: Identifier of burned NFT.210 ///211 /// * owner: which user has destroyed its tokens212 ///213 /// * amount: Always 1 for NFT214 ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),215216 /// Item was transferred217 ///218 /// * collection_id: Id of collection to which item is belong219 ///220 /// * item_id: Id of an item221 ///222 /// * sender: Original owner of item223 ///224 /// * recipient: New owner of item225 ///226 /// * amount: Always 1 for NFT227 Transfer(228 CollectionId,229 TokenId,230 T::CrossAccountId,231 T::CrossAccountId,232 u128,233 ),234235 /// * collection_id236 ///237 /// * item_id238 ///239 /// * sender240 ///241 /// * spender242 ///243 /// * amount244 Approved(245 CollectionId,246 TokenId,247 T::CrossAccountId,248 T::CrossAccountId,249 u128,250 ),251 }252253 #[pallet::error]254 pub enum Error<T> {255 /// This collection does not exist.256 CollectionNotFound,257 /// Sender parameter and item owner must be equal.258 MustBeTokenOwner,259 /// No permission to perform action260 NoPermission,261 /// Collection is not in mint mode.262 PublicMintingNotAllowed,263 /// Address is not in allow list.264 AddressNotInAllowlist,265266 /// Collection name can not be longer than 63 char.267 CollectionNameLimitExceeded,268 /// Collection description can not be longer than 255 char.269 CollectionDescriptionLimitExceeded,270 /// Token prefix can not be longer than 15 char.271 CollectionTokenPrefixLimitExceeded,272 /// Total collections bound exceeded.273 TotalCollectionsLimitExceeded,274 /// variable_data exceeded data limit.275 TokenVariableDataLimitExceeded,276 /// Exceeded max admin amount277 CollectionAdminAmountExceeded,278279 /// Collection settings not allowing items transferring280 TransferNotAllowed,281 /// Account token limit exceeded per collection282 AccountTokenLimitExceeded,283 /// Collection token limit exceeded284 CollectionTokenLimitExceeded,285 /// Metadata flag frozen286 MetadataFlagFrozen,287288 /// Item not exists.289 TokenNotFound,290 /// Item balance not enough.291 TokenValueTooLow,292 /// Requested value more than approved.293 TokenValueNotEnough,294 /// Tried to approve more than owned295 CantApproveMoreThanOwned,296297 /// Can't transfer tokens to ethereum zero address298 AddressIsZero,299 /// Target collection doesn't supports this operation300 UnsupportedOperation,301 }302303 #[pallet::storage]304 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;305 #[pallet::storage]306 pub type DestroyedCollectionCount<T> =307 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;308309 /// Collection info310 #[pallet::storage]311 pub type CollectionById<T> = StorageMap<312 Hasher = Blake2_128Concat,313 Key = CollectionId,314 Value = Collection<T>,315 QueryKind = OptionQuery,316 >;317318 #[pallet::storage]319 pub type AdminAmount<T> = StorageMap<320 Hasher = Blake2_128Concat,321 Key = CollectionId,322 Value = u32,323 QueryKind = ValueQuery,324 >;325326 /// List of collection admins327 #[pallet::storage]328 pub type IsAdmin<T: Config> = StorageNMap<329 Key = (330 Key<Blake2_128Concat, CollectionId>,331 Key<Blake2_128Concat, T::CrossAccountId>,332 ),333 Value = bool,334 QueryKind = ValueQuery,335 >;336337 /// Allowlisted collection users338 #[pallet::storage]339 pub type Allowlist<T: Config> = StorageNMap<340 Key = (341 Key<Blake2_128Concat, CollectionId>,342 Key<Blake2_128Concat, T::CrossAccountId>,343 ),344 Value = bool,345 QueryKind = ValueQuery,346 >;347}348349impl<T: Config> Pallet<T> {350 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens351 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {352 ensure!(353 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,354 <Error<T>>::AddressIsZero355 );356 Ok(())357 }358}359360impl<T: Config> Pallet<T> {361 pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {362 {363 ensure!(364 data.name.len() <= MAX_COLLECTION_NAME_LENGTH,365 Error::<T>::CollectionNameLimitExceeded366 );367 ensure!(368 data.description.len() <= MAX_COLLECTION_DESCRIPTION_LENGTH,369 Error::<T>::CollectionDescriptionLimitExceeded370 );371 ensure!(372 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH,373 Error::<T>::CollectionTokenPrefixLimitExceeded374 );375 }376377 let created_count = <CreatedCollectionCount<T>>::get()378 .0379 .checked_add(1)380 .ok_or(ArithmeticError::Overflow)?;381 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;382 let id = CollectionId(created_count);383384 // bound Total number of collections385 ensure!(386 created_count - destroyed_count < COLLECTION_NUMBER_LIMIT,387 <Error<T>>::TotalCollectionsLimitExceeded388 );389390 // =========391392 // Take a (non-refundable) deposit of collection creation393 {394 let mut imbalance =395 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();396 imbalance.subsume(397 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(398 &T::TreasuryAccountId::get(),399 T::CollectionCreationPrice::get(),400 ),401 );402 <T as Config>::Currency::settle(403 &data.owner,404 imbalance,405 WithdrawReasons::TRANSFER,406 ExistenceRequirement::KeepAlive,407 )408 .map_err(|_| Error::<T>::NoPermission)?;409 }410411 <CreatedCollectionCount<T>>::put(created_count);412 <Pallet<T>>::deposit_event(Event::CollectionCreated(413 id,414 data.mode.id(),415 data.owner.clone(),416 ));417 <CollectionById<T>>::insert(id, data);418 Ok(id)419 }420421 pub fn destroy_collection(422 collection: CollectionHandle<T>,423 sender: &T::CrossAccountId,424 ) -> DispatchResult {425 ensure!(426 collection.limits.owner_can_destroy(),427 <Error<T>>::NoPermission,428 );429 collection.check_is_owner(&sender)?;430431 let destroyed_collections = <DestroyedCollectionCount<T>>::get()432 .0433 .checked_add(1)434 .ok_or(ArithmeticError::Overflow)?;435436 // =========437438 <DestroyedCollectionCount<T>>::put(destroyed_collections);439 <CollectionById<T>>::remove(collection.id);440 <AdminAmount<T>>::remove(collection.id);441 <IsAdmin<T>>::remove_prefix((collection.id,), None);442 <Allowlist<T>>::remove_prefix((collection.id,), None);443 Ok(())444 }445446 pub fn toggle_allowlist(447 collection: &CollectionHandle<T>,448 sender: &T::CrossAccountId,449 user: &T::CrossAccountId,450 allowed: bool,451 ) -> DispatchResult {452 collection.check_is_owner_or_admin(&sender)?;453454 // =========455456 if allowed {457 <Allowlist<T>>::insert((collection.id, user), true);458 } else {459 <Allowlist<T>>::remove((collection.id, user));460 }461462 Ok(())463 }464465 pub fn toggle_admin(466 collection: &CollectionHandle<T>,467 sender: &T::CrossAccountId,468 user: &T::CrossAccountId,469 admin: bool,470 ) -> DispatchResult {471 collection.check_is_owner_or_admin(&sender)?;472473 let was_admin = <IsAdmin<T>>::get((collection.id, user));474 if was_admin == admin {475 return Ok(());476 }477 let amount = <AdminAmount<T>>::get(collection.id);478479 if admin {480 let amount = amount481 .checked_add(1)482 .ok_or(<Error<T>>::CollectionAdminAmountExceeded)?;483 ensure!(484 amount <= Self::collection_admins_limit(),485 <Error<T>>::CollectionAdminAmountExceeded,486 );487488 // =========489490 <AdminAmount<T>>::insert(collection.id, amount);491 <IsAdmin<T>>::insert((collection.id, user), true);492 } else {493 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));494 <IsAdmin<T>>::remove((collection.id, user));495 }496497 Ok(())498 }499}500501#[macro_export]502macro_rules! unsupported {503 () => {504 Err(<Error<T>>::UnsupportedOperation.into())505 };506}507508/// Worst cases509pub trait CommonWeightInfo {510 fn create_item() -> Weight;511 fn create_multiple_items(amount: u32) -> Weight;512 fn burn_item() -> Weight;513 fn transfer() -> Weight;514 fn approve() -> Weight;515 fn transfer_from() -> Weight;516 fn burn_from() -> Weight;517 fn set_variable_metadata(bytes: u32) -> Weight;518}519520pub trait CommonCollectionOperations<T: Config> {521 fn create_item(522 &self,523 sender: T::CrossAccountId,524 to: T::CrossAccountId,525 data: CreateItemData,526 ) -> DispatchResultWithPostInfo;527 fn create_multiple_items(528 &self,529 sender: T::CrossAccountId,530 to: T::CrossAccountId,531 data: Vec<CreateItemData>,532 ) -> DispatchResultWithPostInfo;533 fn burn_item(534 &self,535 sender: T::CrossAccountId,536 token: TokenId,537 amount: u128,538 ) -> DispatchResultWithPostInfo;539540 fn transfer(541 &self,542 sender: T::CrossAccountId,543 to: T::CrossAccountId,544 token: TokenId,545 amount: u128,546 ) -> DispatchResultWithPostInfo;547 fn approve(548 &self,549 sender: T::CrossAccountId,550 spender: T::CrossAccountId,551 token: TokenId,552 amount: u128,553 ) -> DispatchResultWithPostInfo;554 fn transfer_from(555 &self,556 sender: T::CrossAccountId,557 from: T::CrossAccountId,558 to: T::CrossAccountId,559 token: TokenId,560 amount: u128,561 ) -> DispatchResultWithPostInfo;562 fn burn_from(563 &self,564 sender: T::CrossAccountId,565 from: T::CrossAccountId,566 token: TokenId,567 amount: u128,568 ) -> DispatchResultWithPostInfo;569570 fn set_variable_metadata(571 &self,572 sender: T::CrossAccountId,573 token: TokenId,574 data: Vec<u8>,575 ) -> DispatchResultWithPostInfo;576577 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;578 fn token_exists(&self, token: TokenId) -> bool;579 fn last_token_id(&self) -> TokenId;580581 fn token_owner(&self, token: TokenId) -> T::CrossAccountId;582 fn const_metadata(&self, token: TokenId) -> Vec<u8>;583 fn variable_metadata(&self, token: TokenId) -> Vec<u8>;584585 /// How many tokens collection contains (Applicable to nonfungible/refungible)586 fn collection_tokens(&self) -> u32;587 /// Amount of different tokens account has (Applicable to nonfungible/refungible)588 fn account_balance(&self, account: T::CrossAccountId) -> u32;589 /// Amount of specific token account have (Applicable to fungible/refungible)590 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;591 fn allowance(592 &self,593 sender: T::CrossAccountId,594 spender: T::CrossAccountId,595 token: TokenId,596 ) -> u128;597}598599// Flexible enough for implementing CommonCollectionOperations600pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {601 let post_info = PostDispatchInfo {602 actual_weight: Some(weight),603 pays_fee: Pays::Yes,604 };605 match res {606 Ok(()) => Ok(post_info),607 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),608 }609}pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -91,8 +91,8 @@
}
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
- PalletCommon::init_collection(data)
+ pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
+ <PalletCommon<T>>::init_collection(data)
}
pub fn destroy_collection(
collection: FungibleHandle<T>,
pallets/nft/src/eth/sponsoring.rsdiffbeforeafterboth--- a/pallets/nft/src/eth/sponsoring.rs
+++ b/pallets/nft/src/eth/sponsoring.rs
@@ -25,7 +25,7 @@
fn try_sponsor<T: Config>(
caller: &H160,
collection_id: CollectionId,
- collection: &Collection<T>,
+ collection: &Collection<T::AccountId>,
call: &[u8],
) -> Result<(), AnyError> {
let (method_id, mut reader) = AbiReader::new_call(call).map_err(|_| AnyError)?;
@@ -109,7 +109,7 @@
if !collection.sponsorship.confirmed() {
return None;
}
- if try_sponsor(who, collection_id, &collection, &call.1).is_ok() {
+ if try_sponsor::<T>(who, collection_id, &collection, &call.1).is_ok() {
return collection
.sponsorship
.sponsor()
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -42,8 +42,8 @@
CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
};
use pallet_common::{
- account::CrossAccountId, CollectionHandle, IsAdmin, Pallet as PalletCommon,
- Error as CommonError, CommonWeightInfo, Allowlist,
+ account::CrossAccountId, CollectionHandle, Pallet as PalletCommon, Error as CommonError,
+ CommonWeightInfo,
};
use pallet_refungible::{Pallet as PalletRefungible, RefungibleHandle};
use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};
@@ -190,7 +190,7 @@
let who = ensure_signed(origin)?;
// Create new collection
- let new_collection = Collection::<T> {
+ let new_collection = Collection {
owner: who.clone(),
name: collection_name,
mode: mode.clone(),
@@ -208,14 +208,14 @@
};
let _id = match mode {
- CollectionMode::NFT => {PalletNonfungible::init_collection(new_collection)?},
+ CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(new_collection)?},
CollectionMode::Fungible(decimal_points) => {
// check params
ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
- PalletFungible::init_collection(new_collection)?
+ <PalletFungible<T>>::init_collection(new_collection)?
}
CollectionMode::ReFungible => {
- PalletRefungible::init_collection(new_collection)?
+ <PalletRefungible<T>>::init_collection(new_collection)?
}
};
@@ -936,19 +936,5 @@
target_collection.save()
}
- }
-}
-
-// TODO: limit returned entries?
-impl<T: Config> Pallet<T> {
- pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
- <IsAdmin<T>>::iter_prefix((collection,))
- .map(|(a, _)| a)
- .collect()
- }
- pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {
- <Allowlist<T>>::iter_prefix((collection,))
- .map(|(a, _)| a)
- .collect()
}
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -133,8 +133,8 @@
// unchecked calls skips any permission checks
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
- PalletCommon::init_collection(data)
+ pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
+ <PalletCommon<T>>::init_collection(data)
}
pub fn destroy_collection(
collection: NonfungibleHandle<T>,
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -156,8 +156,8 @@
// unchecked calls skips any permission checks
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {
- PalletCommon::init_collection(data)
+ pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
+ <PalletCommon<T>>::init_collection(data)
}
pub fn destroy_collection(
collection: RefungibleHandle<T>,
primitives/nft/src/lib.rsdiffbeforeafterboth--- a/primitives/nft/src/lib.rs
+++ b/primitives/nft/src/lib.rs
@@ -207,8 +207,8 @@
#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-pub struct Collection<T: frame_system::Config> {
- pub owner: T::AccountId,
+pub struct Collection<AccountId> {
+ pub owner: AccountId,
pub mode: CollectionMode,
pub access: AccessMode,
pub name: Vec<u16>, // 64 include null escape char
@@ -217,7 +217,7 @@
pub mint_mode: bool,
pub offchain_schema: Vec<u8>,
pub schema_version: SchemaVersion,
- pub sponsorship: SponsorshipState<T::AccountId>,
+ pub sponsorship: SponsorshipState<AccountId>,
pub limits: CollectionLimits, // Collection private restrictions
pub variable_on_chain_schema: Vec<u8>, //
pub const_on_chain_schema: Vec<u8>, //
@@ -413,3 +413,11 @@
CreateItemData::Fungible(item)
}
}
+
+#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+pub struct CollectionStats {
+ pub created: u32,
+ pub destroyed: u32,
+ pub alive: u32,
+}
primitives/rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -1,6 +1,6 @@
#![cfg_attr(not(feature = "std"), no_std)]
-use nft_data_structs::{CollectionId, TokenId};
+use nft_data_structs::{CollectionId, TokenId, Collection, CollectionStats};
use sp_std::vec::Vec;
use sp_core::H160;
use codec::Decode;
@@ -32,6 +32,9 @@
fn adminlist(collection: CollectionId) -> Vec<CrossAccountId>;
fn allowlist(collection: CollectionId) -> Vec<CrossAccountId>;
+ fn allowed(collection: CollectionId, user: CrossAccountId) -> bool;
fn last_token_id(collection: CollectionId) -> TokenId;
+ fn collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>>;
+ fn collection_stats() -> CollectionStats;
}
}
runtime/src/lib.rsdiffbeforeafterboth--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -1040,14 +1040,23 @@
.or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))
}
fn adminlist(collection: CollectionId) -> Vec<CrossAccountId> {
- <pallet_nft::Pallet<Runtime>>::adminlist(collection)
+ <pallet_common::Pallet<Runtime>>::adminlist(collection)
}
fn allowlist(collection: CollectionId) -> Vec<CrossAccountId> {
- <pallet_nft::Pallet<Runtime>>::allowlist(collection)
+ <pallet_common::Pallet<Runtime>>::allowlist(collection)
+ }
+ fn allowed(collection: CollectionId, user: CrossAccountId) -> bool {
+ <pallet_common::Pallet<Runtime>>::allowed(collection, user)
}
fn last_token_id(collection: CollectionId) -> TokenId {
dispatch_nft_runtime!(collection.last_token_id())
}
+ fn collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>> {
+ <pallet_common::CollectionById<Runtime>>::get(collection)
+ }
+ fn collection_stats() -> CollectionStats {
+ <pallet_common::Pallet<Runtime>>::collection_stats()
+ }
}
impl sp_api::Core<Block> for Runtime {
tests/src/addCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/addCollectionAdmin.test.ts
+++ b/tests/src/addCollectionAdmin.test.ts
@@ -8,7 +8,7 @@
import chaiAsPromised from 'chai-as-promised';
import privateKey from './substrate/privateKey';
import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {addCollectionAdminExpectSuccess, createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId} from './util/helpers';
+import {addCollectionAdminExpectSuccess, createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId, queryCollectionExpectSuccess} from './util/helpers';
chai.use(chaiAsPromised);
const expect = chai.expect;
@@ -20,7 +20,7 @@
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.equal(alice.address);
const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
@@ -38,7 +38,7 @@
const bob = privateKey('//Bob');
const charlie = privateKey('//CHARLIE');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.equal(alice.address);
const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
tests/src/addToAllowList.test.tsdiffbeforeafterboth--- a/tests/src/addToAllowList.test.ts
+++ b/tests/src/addToAllowList.test.ts
@@ -18,6 +18,7 @@
normalizeAccountId,
addCollectionAdminExpectSuccess,
addToAllowListExpectFail,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -55,7 +56,7 @@
it('Allow list an address in the collection that does not exist', async () => {
await usingApi(async (api) => {
// tslint:disable-next-line: no-bitwise
- const collectionId = ((await api.query.common.createdCollectionCount()).toNumber()) + 1;
+ const collectionId = await getCreatedCollectionCount(api) + 1;
const bob = privateKey('//Bob');
const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(bob.address));
tests/src/approve.test.tsdiffbeforeafterboth--- a/tests/src/approve.test.ts
+++ b/tests/src/approve.test.ts
@@ -18,6 +18,7 @@
transferExpectSuccess,
addCollectionAdminExpectSuccess,
adminApproveFromExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -94,13 +95,13 @@
it('Approve for a collection that does not exist', async () => {
await usingApi(async (api: ApiPromise) => {
// nft
- const nftCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const nftCollectionCount = await getCreatedCollectionCount(api);
await approveExpectFail(nftCollectionCount + 1, 1, alice, bob);
// fungible
- const fungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const fungibleCollectionCount = await getCreatedCollectionCount(api);
await approveExpectFail(fungibleCollectionCount + 1, 0, alice, bob);
// reFungible
- const reFungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const reFungibleCollectionCount = await getCreatedCollectionCount(api);
await approveExpectFail(reFungibleCollectionCount + 1, 1, alice, bob);
});
});
tests/src/change-collection-owner.test.tsdiffbeforeafterboth--- a/tests/src/change-collection-owner.test.ts
+++ b/tests/src/change-collection-owner.test.ts
@@ -22,6 +22,7 @@
setMintPermissionExpectFailure,
destroyCollectionExpectFailure,
setPublicAccessModeExpectSuccess,
+ queryCollectionExpectSuccess,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -34,13 +35,13 @@
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection =await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.deep.eq(alice.address);
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await submitTransactionAsync(alice, changeOwnerTx);
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
});
});
@@ -53,7 +54,7 @@
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.deep.eq(alice.address);
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
@@ -62,7 +63,7 @@
const badChangeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, alice.address);
await expect(submitTransactionExpectFailAsync(alice, badChangeOwnerTx)).to.be.rejected;
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
});
});
@@ -74,13 +75,13 @@
const bob = privateKey('//Bob');
const charlie = privateKey('//Charlie');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.deep.eq(alice.address);
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await submitTransactionAsync(alice, changeOwnerTx);
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
// After changing the owner of the collection, all privileged methods are available to the new owner
@@ -118,20 +119,20 @@
const bob = privateKey('//Bob');
const charlie = privateKey('//Charlie');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.deep.eq(alice.address);
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await submitTransactionAsync(alice, changeOwnerTx);
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
const changeOwnerTx2 = api.tx.nft.changeCollectionOwner(collectionId, charlie.address);
await submitTransactionAsync(bob, changeOwnerTx2);
// ownership lost
- const collectionAfterOwnerChange2 = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange2 = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange2.owner.toString()).to.be.deep.eq(charlie.address);
});
});
@@ -147,7 +148,7 @@
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await expect(submitTransactionExpectFailAsync(bob, changeOwnerTx)).to.be.rejected;
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(alice.address);
// Verifying that nothing bad happened (network is live, new collections can be created, etc.)
@@ -166,7 +167,7 @@
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
await expect(submitTransactionExpectFailAsync(bob, changeOwnerTx)).to.be.rejected;
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(alice.address);
// Verifying that nothing bad happened (network is live, new collections can be created, etc.)
@@ -195,7 +196,7 @@
const bob = privateKey('//Bob');
const charlie = privateKey('//Charlie');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.deep.eq(alice.address);
const changeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, bob.address);
@@ -204,7 +205,7 @@
const badChangeOwnerTx = api.tx.nft.changeCollectionOwner(collectionId, alice.address);
await expect(submitTransactionExpectFailAsync(alice, badChangeOwnerTx)).to.be.rejected;
- const collectionAfterOwnerChange = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collectionAfterOwnerChange = await queryCollectionExpectSuccess(api, collectionId);
expect(collectionAfterOwnerChange.owner.toString()).to.be.deep.eq(bob.address);
await setCollectionSponsorExpectFailure(collectionId, charlie.address, '//Alice');
tests/src/confirmSponsorship.test.tsdiffbeforeafterboth--- a/tests/src/confirmSponsorship.test.ts
+++ b/tests/src/confirmSponsorship.test.ts
@@ -20,6 +20,7 @@
addToAllowListExpectSuccess,
normalizeAccountId,
addCollectionAdminExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
import {Keyring} from '@polkadot/api';
import {IKeyringPair} from '@polkadot/types/types';
@@ -335,7 +336,7 @@
// Find the collection that never existed
let collectionId = 0;
await usingApi(async (api) => {
- collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ collectionId = await getCreatedCollectionCount(api) + 1;
});
await confirmSponsorshipExpectFailure(collectionId, '//Bob');
tests/src/contracts.test.tsdiffbeforeafterboth--- a/tests/src/contracts.test.ts
+++ b/tests/src/contracts.test.ts
@@ -228,7 +228,7 @@
const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);
await submitTransactionAsync(alice, changeAdminTx);
- expect(await isAllowlisted(collectionId, bob.address)).to.be.false;
+ expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;
{
const transferTx = contract.tx.toggleAllowList(value, gasLimit, collectionId, bob.address, true);
@@ -236,7 +236,7 @@
const result = getGenericResult(events);
expect(result.success).to.be.true;
- expect(await isAllowlisted(collectionId, bob.address)).to.be.true;
+ expect(await isAllowlisted(api, collectionId, bob.address)).to.be.true;
}
{
const transferTx = contract.tx.toggleAllowList(value, gasLimit, collectionId, bob.address, false);
@@ -244,7 +244,7 @@
const result = getGenericResult(events);
expect(result.success).to.be.true;
- expect(await isAllowlisted(collectionId, bob.address)).to.be.false;
+ expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;
}
});
});
tests/src/createMultipleItems.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItems.test.ts
+++ b/tests/src/createMultipleItems.test.ts
@@ -20,6 +20,7 @@
getLastTokenId,
getVariableMetadata,
getConstMetadata,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -273,7 +274,7 @@
it('Create token in not existing collection', async () => {
await usingApi(async (api: ApiPromise) => {
- const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ const collectionId = await getCreatedCollectionCount(api) + 1;
const createMultipleItemsTx = api.tx.nft
.createMultipleItems(collectionId, normalizeAccountId(alice.address), ['NFT', 'NFT', 'NFT']);
await expect(submitTransactionExpectFailAsync(alice, createMultipleItemsTx)).to.be.rejected;
tests/src/destroyCollection.test.tsdiffbeforeafterboth--- a/tests/src/destroyCollection.test.ts
+++ b/tests/src/destroyCollection.test.ts
@@ -13,6 +13,7 @@
destroyCollectionExpectFailure,
setCollectionLimitsExpectSuccess,
addCollectionAdminExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -46,7 +47,7 @@
it('(!negative test!) Destroy a collection that never existed', async () => {
await usingApi(async (api) => {
// Find the collection that never existed
- const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ const collectionId = await getCreatedCollectionCount(api) + 1;
await destroyCollectionExpectFailure(collectionId);
});
});
tests/src/interfaces/augment-api-rpc.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-rpc.ts
+++ b/tests/src/interfaces/augment-api-rpc.ts
@@ -1,7 +1,7 @@
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
/* eslint-disable */
-import type { NftDataStructsCollectionId, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr } from './nft';
+import type { NftDataStructsCollection, NftDataStructsCollectionId, NftDataStructsCollectionStats, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr } from './nft';
import type { Bytes, HashMap, Json, Metadata, Null, Option, StorageKey, Text, U256, U64, Vec, bool, u128, u32, u64 } from '@polkadot/types';
import type { ExtrinsicOrHash, ExtrinsicStatus } from '@polkadot/types/interfaces/author';
import type { EpochAuthorship } from '@polkadot/types/interfaces/babe';
@@ -373,6 +373,10 @@
**/
allowance: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, sender: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, spender: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, tokenId: NftDataStructsTokenId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
/**
+ * Check if user is allowed to use collection
+ **/
+ allowed: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, account: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<bool>>;
+ /**
* Get allowlist
**/
allowlist: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Vec<PalletCommonAccountBasicCrossAccountIdRepr>>>;
@@ -381,6 +385,14 @@
**/
balance: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, account: PalletCommonAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, tokenId: NftDataStructsTokenId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u128>>;
/**
+ * Get collection by specified id
+ **/
+ collectionById: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Option<NftDataStructsCollection>>>;
+ /**
+ * Get collection stats
+ **/
+ collectionStats: AugmentedRpc<(at?: Hash | string | Uint8Array) => Observable<NftDataStructsCollectionStats>>;
+ /**
* Get tokens contained in collection
**/
collectionTokens: AugmentedRpc<(collection: NftDataStructsCollectionId | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Vec<NftDataStructsTokenId>>>;
tests/src/interfaces/augment-types.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-types.ts
+++ b/tests/src/interfaces/augment-types.ts
@@ -2,7 +2,7 @@
/* eslint-disable */
import type { EthereumBlock, EthereumLog, EthereumReceipt, EthereumTransactionLegacyTransaction, EvmCoreErrorExitReason, FpRpcTransactionStatus } from './ethereum';
-import type { NftDataStructsAccessMode, NftDataStructsCollection, NftDataStructsCollectionId, NftDataStructsCollectionLimits, NftDataStructsCollectionMode, NftDataStructsCreateItemData, NftDataStructsMetaUpdatePermission, NftDataStructsSchemaVersion, NftDataStructsSponsorshipState, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr, PalletNonfungibleItemData, PalletRefungibleItemData, PalletUnqSchedulerCallSpec, PalletUnqSchedulerReleases, PalletUnqSchedulerScheduledV2 } from './nft';
+import type { NftDataStructsAccessMode, NftDataStructsCollection, NftDataStructsCollectionId, NftDataStructsCollectionLimits, NftDataStructsCollectionMode, NftDataStructsCollectionStats, NftDataStructsCreateItemData, NftDataStructsMetaUpdatePermission, NftDataStructsSchemaVersion, NftDataStructsSponsorshipState, NftDataStructsTokenId, PalletCommonAccountBasicCrossAccountIdRepr, PalletNonfungibleItemData, PalletRefungibleItemData, PalletUnqSchedulerCallSpec, PalletUnqSchedulerReleases, PalletUnqSchedulerScheduledV2 } from './nft';
import type { CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmpQueueInboundStatus, CumulusPalletXcmpQueueOutboundStatus, CumulusPalletXcmpQueueQueueConfigData, CumulusPrimitivesParachainInherentParachainInherentData, PolkadotParachainPrimitivesXcmpMessageFormat, PolkadotPrimitivesV1AbridgedHostConfiguration, PolkadotPrimitivesV1PersistedValidationData } from './polkadot';
import type { BitVec, Bool, Bytes, Data, I128, I16, I256, I32, I64, I8, Json, Null, Raw, StorageKey, Text, Type, U128, U16, U256, U32, U64, U8, USize, bool, i128, i16, i256, i32, i64, i8, u128, u16, u256, u32, u64, u8, usize } from '@polkadot/types';
import type { AssetApproval, AssetApprovalKey, AssetBalance, AssetDestroyWitness, AssetDetails, AssetMetadata, TAssetBalance, TAssetDepositBalance } from '@polkadot/types/interfaces/assets';
@@ -627,6 +627,7 @@
NftDataStructsCollectionId: NftDataStructsCollectionId;
NftDataStructsCollectionLimits: NftDataStructsCollectionLimits;
NftDataStructsCollectionMode: NftDataStructsCollectionMode;
+ NftDataStructsCollectionStats: NftDataStructsCollectionStats;
NftDataStructsCreateItemData: NftDataStructsCreateItemData;
NftDataStructsMetaUpdatePermission: NftDataStructsMetaUpdatePermission;
NftDataStructsSchemaVersion: NftDataStructsSchemaVersion;
tests/src/interfaces/nft/definitions.tsdiffbeforeafterboth--- a/tests/src/interfaces/nft/definitions.ts
+++ b/tests/src/interfaces/nft/definitions.ts
@@ -40,6 +40,9 @@
constMetadata: fun('Get token constant metadata', [collectionParam, tokenParam], 'Vec<u8>'),
variableMetadata: fun('Get token variable metadata', [collectionParam, tokenParam], 'Vec<u8>'),
tokenExists: fun('Check if token exists', [collectionParam, tokenParam], 'bool'),
+ collectionById: fun('Get collection by specified id', [collectionParam], 'Option<NftDataStructsCollection>'),
+ collectionStats: fun('Get collection stats', [], 'NftDataStructsCollectionStats'),
+ allowed: fun('Check if user is allowed to use collection', [collectionParam, crossAccountParam()], 'bool'),
},
types: {
PalletCommonAccountBasicCrossAccountIdRepr: {
@@ -64,6 +67,11 @@
constOnChainSchema: 'Vec<u8>',
metaUpdatePermission: 'NftDataStructsMetaUpdatePermission',
},
+ NftDataStructsCollectionStats: {
+ created: 'u32',
+ destroyed: 'u32',
+ alive: 'u32',
+ },
NftDataStructsCollectionId: 'u32',
NftDataStructsTokenId: 'u32',
PalletNonfungibleItemData: mkDummy('NftItemData'),
tests/src/interfaces/nft/types.tsdiffbeforeafterboth--- a/tests/src/interfaces/nft/types.ts
+++ b/tests/src/interfaces/nft/types.ts
@@ -48,6 +48,13 @@
readonly dummyCollectionMode: u32;
}
+/** @name NftDataStructsCollectionStats */
+export interface NftDataStructsCollectionStats extends Struct {
+ readonly created: u32;
+ readonly destroyed: u32;
+ readonly alive: u32;
+}
+
/** @name NftDataStructsCreateItemData */
export interface NftDataStructsCreateItemData extends Struct {
readonly dummyCreateItemData: u32;
tests/src/removeCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/removeCollectionAdmin.test.ts
+++ b/tests/src/removeCollectionAdmin.test.ts
@@ -8,7 +8,7 @@
import chaiAsPromised from 'chai-as-promised';
import privateKey from './substrate/privateKey';
import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId} from './util/helpers';
+import {createCollectionExpectSuccess, destroyCollectionExpectSuccess, getAdminList, normalizeAccountId, queryCollectionExpectSuccess} from './util/helpers';
chai.use(chaiAsPromised);
const expect = chai.expect;
@@ -19,7 +19,7 @@
const collectionId = await createCollectionExpectSuccess();
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.deep.eq(alice.address);
// first - add collection admin Bob
const addAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
@@ -43,7 +43,7 @@
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
const charlie = privateKey('//Charlie');
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
// first - add collection admin Bob
const addAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(bob.address));
tests/src/removeCollectionSponsor.test.tsdiffbeforeafterboth--- a/tests/src/removeCollectionSponsor.test.ts
+++ b/tests/src/removeCollectionSponsor.test.ts
@@ -18,6 +18,7 @@
removeCollectionSponsorExpectFailure,
normalizeAccountId,
addCollectionAdminExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
import {Keyring} from '@polkadot/api';
import {IKeyringPair} from '@polkadot/types/types';
@@ -98,7 +99,7 @@
// Find the collection that never existed
let collectionId = 0;
await usingApi(async (api) => {
- collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ collectionId = await getCreatedCollectionCount(api) + 1;
});
await removeCollectionSponsorExpectFailure(collectionId);
tests/src/removeFromAllowList.test.tsdiffbeforeafterboth--- a/tests/src/removeFromAllowList.test.ts
+++ b/tests/src/removeFromAllowList.test.ts
@@ -37,13 +37,13 @@
});
it('ensure bob is not in allowlist after removal', async () => {
- await usingApi(async () => {
+ await usingApi(async api => {
const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
await enableAllowListExpectSuccess(alice, collectionId);
await addToAllowListExpectSuccess(alice, collectionId, bob.address);
await removeFromAllowListExpectSuccess(alice, collectionId, normalizeAccountId(bob.address));
- expect(await isAllowlisted(collectionId, bob.address)).to.be.false;
+ expect(await isAllowlisted(api, collectionId, bob.address)).to.be.false;
});
});
@@ -104,13 +104,13 @@
});
it('ensure address is not in allowlist after removal', async () => {
- await usingApi(async () => {
+ await usingApi(async api => {
const collectionId = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
await enableAllowListExpectSuccess(alice, collectionId);
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
await addToAllowListExpectSuccess(alice, collectionId, charlie.address);
await removeFromAllowListExpectSuccess(bob, collectionId, normalizeAccountId(charlie.address));
- expect(await isAllowlisted(collectionId, charlie.address)).to.be.false;
+ expect(await isAllowlisted(api, collectionId, charlie.address)).to.be.false;
});
});
tests/src/setCollectionSponsor.test.tsdiffbeforeafterboth--- a/tests/src/setCollectionSponsor.test.ts
+++ b/tests/src/setCollectionSponsor.test.ts
@@ -11,6 +11,7 @@
destroyCollectionExpectSuccess,
setCollectionSponsorExpectFailure,
addCollectionAdminExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
import {Keyring} from '@polkadot/api';
import {IKeyringPair} from '@polkadot/types/types';
@@ -77,7 +78,7 @@
// Find the collection that never existed
let collectionId = 0;
await usingApi(async (api) => {
- collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ collectionId = await getCreatedCollectionCount(api) + 1;
});
await setCollectionSponsorExpectFailure(collectionId, bob.address);
tests/src/setConstOnChainSchema.test.tsdiffbeforeafterboth--- a/tests/src/setConstOnChainSchema.test.ts
+++ b/tests/src/setConstOnChainSchema.test.ts
@@ -12,6 +12,8 @@
createCollectionExpectSuccess,
destroyCollectionExpectSuccess,
addCollectionAdminExpectSuccess,
+ queryCollectionExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -37,7 +39,7 @@
it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
await submitTransactionAsync(alice, setShema);
@@ -47,7 +49,7 @@
it('Collection admin can set the scheme', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
@@ -60,7 +62,7 @@
const collectionId = await createCollectionExpectSuccess();
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
await submitTransactionAsync(alice, setShema);
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.constOnChainSchema.toString()).to.be.eq(shema);
});
});
@@ -71,7 +73,7 @@
it('Set a non-existent collection', async () => {
await usingApi(async (api) => {
// tslint:disable-next-line: radix
- const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ const collectionId = await getCreatedCollectionCount(api) + 1;
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
await expect(submitTransactionExpectFailAsync(alice, setShema)).to.be.rejected;
});
@@ -97,7 +99,7 @@
it('Execute method not on behalf of the collection owner', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
const setShema = api.tx.nft.setConstOnChainSchema(collectionId, shema);
await expect(submitTransactionExpectFailAsync(bob, setShema)).to.be.rejected;
tests/src/setPublicAccessMode.test.tsdiffbeforeafterboth--- a/tests/src/setPublicAccessMode.test.ts
+++ b/tests/src/setPublicAccessMode.test.ts
@@ -19,6 +19,7 @@
enableAllowListExpectSuccess,
normalizeAccountId,
addCollectionAdminExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -60,7 +61,7 @@
it('Set a non-existent collection', async () => {
await usingApi(async (api: ApiPromise) => {
// tslint:disable-next-line: radix
- const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ const collectionId = await getCreatedCollectionCount(api) + 1;
const tx = api.tx.nft.setPublicAccessMode(collectionId, 'AllowList');
await expect(submitTransactionExpectFailAsync(alice, tx)).to.be.rejected;
});
tests/src/setVariableOnChainSchema.test.tsdiffbeforeafterboth--- a/tests/src/setVariableOnChainSchema.test.ts
+++ b/tests/src/setVariableOnChainSchema.test.ts
@@ -12,6 +12,8 @@
createCollectionExpectSuccess,
destroyCollectionExpectSuccess,
addCollectionAdminExpectSuccess,
+ queryCollectionExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -37,7 +39,7 @@
it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
await submitTransactionAsync(alice, setSchema);
@@ -49,7 +51,7 @@
const collectionId = await createCollectionExpectSuccess();
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
await submitTransactionAsync(alice, setSchema);
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.variableOnChainSchema.toString()).to.be.eq(schema);
});
@@ -61,7 +63,7 @@
it('Run extrinsic with parameters of the collection id, set the scheme', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
@@ -75,7 +77,7 @@
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
await submitTransactionAsync(bob, setSchema);
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.variableOnChainSchema.toString()).to.be.eq(schema);
});
@@ -87,7 +89,7 @@
it('Set a non-existent collection', async () => {
await usingApi(async (api) => {
// tslint:disable-next-line: radix
- const collectionId = (await api.query.common.createdCollectionCount()).toNumber() + 1;
+ const collectionId = await getCreatedCollectionCount(api) + 1;
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
});
@@ -113,7 +115,7 @@
it('Execute method not on behalf of the collection owner', async () => {
await usingApi(async (api) => {
const collectionId = await createCollectionExpectSuccess();
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.owner.toString()).to.be.eq(alice.address);
const setSchema = api.tx.nft.setVariableOnChainSchema(collectionId, schema);
await expect(submitTransactionExpectFailAsync(bob, setSchema)).to.be.rejected;
tests/src/transfer.test.tsdiffbeforeafterboth--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -19,6 +19,7 @@
transferExpectFailure,
transferExpectSuccess,
addCollectionAdminExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
let alice: IKeyringPair;
@@ -132,13 +133,13 @@
it('Transfer with not existed collection_id', async () => {
await usingApi(async (api) => {
// nft
- const nftCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const nftCollectionCount = await getCreatedCollectionCount(api);
await transferExpectFailure(nftCollectionCount + 1, 1, alice, bob, 1);
// fungible
- const fungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const fungibleCollectionCount = await getCreatedCollectionCount(api);
await transferExpectFailure(fungibleCollectionCount + 1, 0, alice, bob, 1);
// reFungible
- const reFungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const reFungibleCollectionCount = await getCreatedCollectionCount(api);
await transferExpectFailure(reFungibleCollectionCount + 1, 1, alice, bob, 1);
});
});
tests/src/transferFrom.test.tsdiffbeforeafterboth--- a/tests/src/transferFrom.test.ts
+++ b/tests/src/transferFrom.test.ts
@@ -19,6 +19,7 @@
transferFromExpectSuccess,
burnItemExpectSuccess,
setCollectionLimitsExpectSuccess,
+ getCreatedCollectionCount,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -109,18 +110,18 @@
it('transferFrom for a collection that does not exist', async () => {
await usingApi(async (api: ApiPromise) => {
// nft
- const nftCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const nftCollectionCount = await getCreatedCollectionCount(api);
await approveExpectFail(nftCollectionCount + 1, 1, alice, bob);
await transferFromExpectFail(nftCollectionCount + 1, 1, bob, alice, charlie, 1);
// fungible
- const fungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const fungibleCollectionCount = await getCreatedCollectionCount(api);
await approveExpectFail(fungibleCollectionCount + 1, 0, alice, bob);
await transferFromExpectFail(fungibleCollectionCount + 1, 0, bob, alice, charlie, 1);
// reFungible
- const reFungibleCollectionCount = (await api.query.common.createdCollectionCount()).toNumber();
+ const reFungibleCollectionCount = await getCreatedCollectionCount(api);
await approveExpectFail(reFungibleCollectionCount + 1, 1, alice, bob);
await transferFromExpectFail(reFungibleCollectionCount + 1, 1, bob, alice, charlie, 1);
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -269,7 +269,7 @@
let collectionId = 0;
await usingApi(async (api) => {
// Get number of collections before the transaction
- const collectionCountBefore = (await api.query.common.createdCollectionCount()).toNumber();
+ const collectionCountBefore = await getCreatedCollectionCount(api);
// Run the CreateCollection transaction
const alicePrivateKey = privateKey('//Alice');
@@ -288,10 +288,10 @@
const result = getCreateCollectionResult(events);
// Get number of collections after the transaction
- const collectionCountAfter = (await api.query.common.createdCollectionCount()).toNumber();
+ const collectionCountAfter = await getCreatedCollectionCount(api);
// Get the collection
- const collection = (await api.query.common.collectionById(result.collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, result.collectionId);
// What to expect
// tslint:disable-next-line:no-unused-expression
@@ -325,7 +325,7 @@
await usingApi(async (api) => {
// Get number of collections before the transaction
- const collectionCountBefore = (await api.query.common.createdCollectionCount()).toNumber();
+ const collectionCountBefore = await getCreatedCollectionCount(api);
// Run the CreateCollection transaction
const alicePrivateKey = privateKey('//Alice');
@@ -334,7 +334,7 @@
const result = getCreateCollectionResult(events);
// Get number of collections after the transaction
- const collectionCountAfter = (await api.query.common.createdCollectionCount()).toNumber();
+ const collectionCountAfter = await getCreatedCollectionCount(api);
// What to expect
// tslint:disable-next-line:no-unused-expression
@@ -364,7 +364,7 @@
}
export async function findNotExistingCollection(api: ApiPromise): Promise<number> {
- const totalNumber = (await api.query.common.createdCollectionCount()).toNumber();
+ const totalNumber = await getCreatedCollectionCount(api);
const newCollection: number = totalNumber + 1;
return newCollection;
}
@@ -398,7 +398,7 @@
expect(result).to.be.true;
// What to expect
- expect((await api.query.common.collectionById(collectionId)).isNone).to.be.true;
+ expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;
});
}
@@ -432,7 +432,7 @@
const result = getGenericResult(events);
// Get the collection
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
// What to expect
expect(result.success).to.be.true;
@@ -452,7 +452,7 @@
const result = getGenericResult(events);
// Get the collection
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
// What to expect
expect(result.success).to.be.true;
@@ -490,7 +490,7 @@
const result = getGenericResult(events);
// Get the collection
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
// What to expect
expect(result.success).to.be.true;
@@ -1057,7 +1057,7 @@
const result = getGenericResult(events);
// Get the collection
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
// What to expect
// tslint:disable-next-line:no-unused-expression
@@ -1105,7 +1105,7 @@
expect(result.success).to.be.true;
// Get the collection
- const collection = (await api.query.common.collectionById(collectionId)).unwrap();
+ const collection = await queryCollectionExpectSuccess(api, collectionId);
expect(collection.mintMode.toHuman()).to.be.equal(enabled);
});
@@ -1137,15 +1137,13 @@
});
}
-export async function isAllowlisted(collectionId: number, address: string | CrossAccountId) {
- return await usingApi(async (api) => {
- return (await api.query.common.allowlist(collectionId, normalizeAccountId(address))).toJSON();
- });
+export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {
+ return (await api.rpc.nft.allowed(collectionId, normalizeAccountId(address))).toJSON();
}
export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {
await usingApi(async (api) => {
- expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.false;
+ expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;
// Run the transaction
const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));
@@ -1153,14 +1151,14 @@
const result = getGenericResult(events);
expect(result.success).to.be.true;
- expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;
+ expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
});
}
export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {
await usingApi(async (api) => {
- expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;
+ expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
// Run the transaction
const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));
@@ -1168,7 +1166,7 @@
const result = getGenericResult(events);
expect(result.success).to.be.true;
- expect(await isAllowlisted(collectionId, normalizeAccountId(address))).to.be.true;
+ expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;
});
}
@@ -1214,16 +1212,16 @@
export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)
: Promise<NftDataStructsCollection | null> => {
- return (await api.query.common.collectionById(collectionId)).unwrapOr(null);
+ return (await api.rpc.nft.collectionById(collectionId)).unwrapOr(null);
};
export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {
// set global object - collectionsCount
- return (await api.query.common.createdCollectionCount()).toNumber();
+ return (await api.rpc.nft.collectionStats()).created.toNumber();
};
export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<NftDataStructsCollection> {
- return (await api.query.common.collectionById(collectionId)).unwrap();
+ return (await api.rpc.nft.collectionById(collectionId)).unwrap();
}
export async function waitNewBlocks(blocksCount = 1): Promise<void> {