difftreelog
Merge pull request #277 from UniqueNetwork/feature/create-collection-ex
in: master
Add createCollectionEx call
18 files changed
pallets/common/src/lib.rsdiffbeforeafterboth1#![cfg_attr(not(feature = "std"), no_std)]23use core::ops::{Deref, DerefMut};4use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};5use sp_std::vec::Vec;6use account::CrossAccountId;7use frame_support::{8 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo},9 ensure, fail,10 traits::{Imbalance, Get, Currency},11 BoundedVec,12};13use pallet_evm::GasWeightMapping;14use up_data_structs::{15 COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,16 MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo,17 TokenId, Weight, WithdrawReasons, CollectionStats, CustomDataLimit,18};19pub use pallet::*;20use sp_core::H160;21use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};22pub mod account;23#[cfg(feature = "runtime-benchmarks")]24pub mod benchmarking;25pub mod erc;26pub mod eth;2728#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]29pub struct CollectionHandle<T: Config> {30 pub id: CollectionId,31 collection: Collection<T::AccountId>,32 pub recorder: SubstrateRecorder<T>,33}34impl<T: Config> WithRecorder<T> for CollectionHandle<T> {35 fn recorder(&self) -> &SubstrateRecorder<T> {36 &self.recorder37 }38 fn into_recorder(self) -> SubstrateRecorder<T> {39 self.recorder40 }41}42impl<T: Config> CollectionHandle<T> {43 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {44 <CollectionById<T>>::get(id).map(|collection| Self {45 id,46 collection,47 recorder: SubstrateRecorder::new(eth::collection_id_to_address(id), gas_limit),48 })49 }50 pub fn new(id: CollectionId) -> Option<Self> {51 Self::new_with_gas_limit(id, u64::MAX)52 }53 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {54 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)55 }56 pub fn log_mirrored(&self, log: impl evm_coder::ToLog) {57 self.recorder.log_mirrored(log)58 }59 pub fn log_direct(&self, log: impl evm_coder::ToLog) {60 self.recorder.log_direct(log)61 }62 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {63 self.recorder64 .consume_gas(T::GasWeightMapping::weight_to_gas(65 <T as frame_system::Config>::DbWeight::get()66 .read67 .saturating_mul(reads),68 ))69 }70 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {71 self.recorder72 .consume_gas(T::GasWeightMapping::weight_to_gas(73 <T as frame_system::Config>::DbWeight::get()74 .write75 .saturating_mul(writes),76 ))77 }78 pub fn submit_logs(self) {79 self.recorder.submit_logs()80 }81 pub fn save(self) -> DispatchResult {82 self.recorder.submit_logs();83 <CollectionById<T>>::insert(self.id, self.collection);84 Ok(())85 }86}87impl<T: Config> Deref for CollectionHandle<T> {88 type Target = Collection<T::AccountId>;8990 fn deref(&self) -> &Self::Target {91 &self.collection92 }93}9495impl<T: Config> DerefMut for CollectionHandle<T> {96 fn deref_mut(&mut self) -> &mut Self::Target {97 &mut self.collection98 }99}100101impl<T: Config> CollectionHandle<T> {102 pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {103 ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);104 Ok(())105 }106 pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> bool {107 *subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject))108 }109 pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {110 ensure!(self.is_owner_or_admin(subject), <Error<T>>::NoPermission);111 Ok(())112 }113 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {114 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)115 }116 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {117 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)118 }119 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {120 ensure!(121 <Allowlist<T>>::get((self.id, user)),122 <Error<T>>::AddressNotInAllowlist123 );124 Ok(())125 }126127 pub fn check_can_update_meta(128 &self,129 subject: &T::CrossAccountId,130 item_owner: &T::CrossAccountId,131 ) -> DispatchResult {132 match self.meta_update_permission {133 MetaUpdatePermission::ItemOwner => {134 ensure!(subject == item_owner, <Error<T>>::NoPermission);135 Ok(())136 }137 MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),138 MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),139 }140 }141}142143#[frame_support::pallet]144pub mod pallet {145 use super::*;146 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key};147 use account::CrossAccountId;148 use frame_support::traits::Currency;149 use up_data_structs::TokenId;150 use scale_info::TypeInfo;151152 #[pallet::config]153 pub trait Config: frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo {154 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;155156 type CrossAccountId: CrossAccountId<Self::AccountId>;157158 type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;159 type EvmBackwardsAddressMapping: up_evm_mapping::EvmBackwardsAddressMapping<Self::AccountId>;160161 type Currency: Currency<Self::AccountId>;162 type CollectionCreationPrice: Get<163 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,164 >;165 type TreasuryAccountId: Get<Self::AccountId>;166 }167168 #[pallet::pallet]169 #[pallet::generate_store(pub(super) trait Store)]170 pub struct Pallet<T>(_);171172 #[pallet::extra_constants]173 impl<T: Config> Pallet<T> {174 pub fn collection_admins_limit() -> u32 {175 COLLECTION_ADMINS_LIMIT176 }177 }178179 #[pallet::event]180 #[pallet::generate_deposit(pub fn deposit_event)]181 pub enum Event<T: Config> {182 /// New collection was created183 ///184 /// # Arguments185 ///186 /// * collection_id: Globally unique identifier of newly created collection.187 ///188 /// * mode: [CollectionMode] converted into u8.189 ///190 /// * account_id: Collection owner.191 CollectionCreated(CollectionId, u8, T::AccountId),192193 /// New collection was destroyed194 ///195 /// # Arguments196 ///197 /// * collection_id: Globally unique identifier of collection.198 CollectionDestroyed(CollectionId),199200 /// New item was created.201 ///202 /// # Arguments203 ///204 /// * collection_id: Id of the collection where item was created.205 ///206 /// * item_id: Id of an item. Unique within the collection.207 ///208 /// * recipient: Owner of newly created item209 ///210 /// * amount: Always 1 for NFT211 ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),212213 /// Collection item was burned.214 ///215 /// # Arguments216 ///217 /// * collection_id.218 ///219 /// * item_id: Identifier of burned NFT.220 ///221 /// * owner: which user has destroyed its tokens222 ///223 /// * amount: Always 1 for NFT224 ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),225226 /// Item was transferred227 ///228 /// * collection_id: Id of collection to which item is belong229 ///230 /// * item_id: Id of an item231 ///232 /// * sender: Original owner of item233 ///234 /// * recipient: New owner of item235 ///236 /// * amount: Always 1 for NFT237 Transfer(238 CollectionId,239 TokenId,240 T::CrossAccountId,241 T::CrossAccountId,242 u128,243 ),244245 /// * collection_id246 ///247 /// * item_id248 ///249 /// * sender250 ///251 /// * spender252 ///253 /// * amount254 Approved(255 CollectionId,256 TokenId,257 T::CrossAccountId,258 T::CrossAccountId,259 u128,260 ),261 }262263 #[pallet::error]264 pub enum Error<T> {265 /// This collection does not exist.266 CollectionNotFound,267 /// Sender parameter and item owner must be equal.268 MustBeTokenOwner,269 /// No permission to perform action270 NoPermission,271 /// Collection is not in mint mode.272 PublicMintingNotAllowed,273 /// Address is not in allow list.274 AddressNotInAllowlist,275276 /// Collection name can not be longer than 63 char.277 CollectionNameLimitExceeded,278 /// Collection description can not be longer than 255 char.279 CollectionDescriptionLimitExceeded,280 /// Token prefix can not be longer than 15 char.281 CollectionTokenPrefixLimitExceeded,282 /// Total collections bound exceeded.283 TotalCollectionsLimitExceeded,284 /// variable_data exceeded data limit.285 TokenVariableDataLimitExceeded,286 /// Exceeded max admin count287 CollectionAdminCountExceeded,288289 /// Collection settings not allowing items transferring290 TransferNotAllowed,291 /// Account token limit exceeded per collection292 AccountTokenLimitExceeded,293 /// Collection token limit exceeded294 CollectionTokenLimitExceeded,295 /// Metadata flag frozen296 MetadataFlagFrozen,297298 /// Item not exists.299 TokenNotFound,300 /// Item balance not enough.301 TokenValueTooLow,302 /// Requested value more than approved.303 TokenValueNotEnough,304 /// Tried to approve more than owned305 CantApproveMoreThanOwned,306307 /// Can't transfer tokens to ethereum zero address308 AddressIsZero,309 /// Target collection doesn't supports this operation310 UnsupportedOperation,311 }312313 #[pallet::storage]314 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;315 #[pallet::storage]316 pub type DestroyedCollectionCount<T> =317 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;318319 /// Collection info320 #[pallet::storage]321 pub type CollectionById<T> = StorageMap<322 Hasher = Blake2_128Concat,323 Key = CollectionId,324 Value = Collection<<T as frame_system::Config>::AccountId>,325 QueryKind = OptionQuery,326 >;327328 #[pallet::storage]329 pub type AdminAmount<T> = StorageMap<330 Hasher = Blake2_128Concat,331 Key = CollectionId,332 Value = u32,333 QueryKind = ValueQuery,334 >;335336 /// List of collection admins337 #[pallet::storage]338 pub type IsAdmin<T: Config> = StorageNMap<339 Key = (340 Key<Blake2_128Concat, CollectionId>,341 Key<Blake2_128Concat, T::CrossAccountId>,342 ),343 Value = bool,344 QueryKind = ValueQuery,345 >;346347 /// Allowlisted collection users348 #[pallet::storage]349 pub type Allowlist<T: Config> = StorageNMap<350 Key = (351 Key<Blake2_128Concat, CollectionId>,352 Key<Blake2_128Concat, T::CrossAccountId>,353 ),354 Value = bool,355 QueryKind = ValueQuery,356 >;357358 /// Not used by code, exists only to provide some types to metadata359 #[pallet::storage]360 pub type DummyStorageValue<T> =361 StorageValue<Value = (CollectionStats, CollectionId, TokenId), QueryKind = OptionQuery>;362}363364impl<T: Config> Pallet<T> {365 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens366 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {367 ensure!(368 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,369 <Error<T>>::AddressIsZero370 );371 Ok(())372 }373 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {374 <IsAdmin<T>>::iter_prefix((collection,))375 .map(|(a, _)| a)376 .collect()377 }378 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {379 <Allowlist<T>>::iter_prefix((collection,))380 .map(|(a, _)| a)381 .collect()382 }383 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {384 <Allowlist<T>>::get((collection, user))385 }386 pub fn collection_stats() -> CollectionStats {387 let created = <CreatedCollectionCount<T>>::get();388 let destroyed = <DestroyedCollectionCount<T>>::get();389 CollectionStats {390 created: created.0,391 destroyed: destroyed.0,392 alive: created.0 - destroyed.0,393 }394 }395}396397impl<T: Config> Pallet<T> {398 pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {399 {400 ensure!(401 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,402 Error::<T>::CollectionTokenPrefixLimitExceeded403 );404 }405406 let created_count = <CreatedCollectionCount<T>>::get()407 .0408 .checked_add(1)409 .ok_or(ArithmeticError::Overflow)?;410 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;411 let id = CollectionId(created_count);412413 // bound Total number of collections414 ensure!(415 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,416 <Error<T>>::TotalCollectionsLimitExceeded417 );418419 // =========420421 // Take a (non-refundable) deposit of collection creation422 {423 let mut imbalance =424 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();425 imbalance.subsume(426 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(427 &T::TreasuryAccountId::get(),428 T::CollectionCreationPrice::get(),429 ),430 );431 <T as Config>::Currency::settle(432 &data.owner,433 imbalance,434 WithdrawReasons::TRANSFER,435 ExistenceRequirement::KeepAlive,436 )437 .map_err(|_| Error::<T>::NoPermission)?;438 }439440 <CreatedCollectionCount<T>>::put(created_count);441 <Pallet<T>>::deposit_event(Event::CollectionCreated(442 id,443 data.mode.id(),444 data.owner.clone(),445 ));446 <CollectionById<T>>::insert(id, data);447 Ok(id)448 }449450 pub fn destroy_collection(451 collection: CollectionHandle<T>,452 sender: &T::CrossAccountId,453 ) -> DispatchResult {454 ensure!(455 collection.limits.owner_can_destroy(),456 <Error<T>>::NoPermission,457 );458 collection.check_is_owner(sender)?;459460 let destroyed_collections = <DestroyedCollectionCount<T>>::get()461 .0462 .checked_add(1)463 .ok_or(ArithmeticError::Overflow)?;464465 // =========466467 <DestroyedCollectionCount<T>>::put(destroyed_collections);468 <CollectionById<T>>::remove(collection.id);469 <AdminAmount<T>>::remove(collection.id);470 <IsAdmin<T>>::remove_prefix((collection.id,), None);471 <Allowlist<T>>::remove_prefix((collection.id,), None);472473 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));474 Ok(())475 }476477 pub fn toggle_allowlist(478 collection: &CollectionHandle<T>,479 sender: &T::CrossAccountId,480 user: &T::CrossAccountId,481 allowed: bool,482 ) -> DispatchResult {483 collection.check_is_owner_or_admin(sender)?;484485 // =========486487 if allowed {488 <Allowlist<T>>::insert((collection.id, user), true);489 } else {490 <Allowlist<T>>::remove((collection.id, user));491 }492493 Ok(())494 }495496 pub fn toggle_admin(497 collection: &CollectionHandle<T>,498 sender: &T::CrossAccountId,499 user: &T::CrossAccountId,500 admin: bool,501 ) -> DispatchResult {502 collection.check_is_owner_or_admin(sender)?;503504 let was_admin = <IsAdmin<T>>::get((collection.id, user));505 if was_admin == admin {506 return Ok(());507 }508 let amount = <AdminAmount<T>>::get(collection.id);509510 if admin {511 let amount = amount512 .checked_add(1)513 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;514 ensure!(515 amount <= Self::collection_admins_limit(),516 <Error<T>>::CollectionAdminCountExceeded,517 );518519 // =========520521 <AdminAmount<T>>::insert(collection.id, amount);522 <IsAdmin<T>>::insert((collection.id, user), true);523 } else {524 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));525 <IsAdmin<T>>::remove((collection.id, user));526 }527528 Ok(())529 }530}531532#[macro_export]533macro_rules! unsupported {534 () => {535 Err(<Error<T>>::UnsupportedOperation.into())536 };537}538539/// Worst cases540pub trait CommonWeightInfo {541 fn create_item() -> Weight;542 fn create_multiple_items(amount: u32) -> Weight;543 fn burn_item() -> Weight;544 fn transfer() -> Weight;545 fn approve() -> Weight;546 fn transfer_from() -> Weight;547 fn burn_from() -> Weight;548 fn set_variable_metadata(bytes: u32) -> Weight;549}550551pub trait CommonCollectionOperations<T: Config> {552 fn create_item(553 &self,554 sender: T::CrossAccountId,555 to: T::CrossAccountId,556 data: CreateItemData,557 ) -> DispatchResultWithPostInfo;558 fn create_multiple_items(559 &self,560 sender: T::CrossAccountId,561 to: T::CrossAccountId,562 data: Vec<CreateItemData>,563 ) -> DispatchResultWithPostInfo;564 fn burn_item(565 &self,566 sender: T::CrossAccountId,567 token: TokenId,568 amount: u128,569 ) -> DispatchResultWithPostInfo;570571 fn transfer(572 &self,573 sender: T::CrossAccountId,574 to: T::CrossAccountId,575 token: TokenId,576 amount: u128,577 ) -> DispatchResultWithPostInfo;578 fn approve(579 &self,580 sender: T::CrossAccountId,581 spender: T::CrossAccountId,582 token: TokenId,583 amount: u128,584 ) -> DispatchResultWithPostInfo;585 fn transfer_from(586 &self,587 sender: T::CrossAccountId,588 from: T::CrossAccountId,589 to: T::CrossAccountId,590 token: TokenId,591 amount: u128,592 ) -> DispatchResultWithPostInfo;593 fn burn_from(594 &self,595 sender: T::CrossAccountId,596 from: T::CrossAccountId,597 token: TokenId,598 amount: u128,599 ) -> DispatchResultWithPostInfo;600601 fn set_variable_metadata(602 &self,603 sender: T::CrossAccountId,604 token: TokenId,605 data: BoundedVec<u8, CustomDataLimit>,606 ) -> DispatchResultWithPostInfo;607608 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;609 fn token_exists(&self, token: TokenId) -> bool;610 fn last_token_id(&self) -> TokenId;611612 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;613 fn const_metadata(&self, token: TokenId) -> Vec<u8>;614 fn variable_metadata(&self, token: TokenId) -> Vec<u8>;615616 /// How many tokens collection contains (Applicable to nonfungible/refungible)617 fn collection_tokens(&self) -> u32;618 /// Amount of different tokens account has (Applicable to nonfungible/refungible)619 fn account_balance(&self, account: T::CrossAccountId) -> u32;620 /// Amount of specific token account have (Applicable to fungible/refungible)621 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;622 fn allowance(623 &self,624 sender: T::CrossAccountId,625 spender: T::CrossAccountId,626 token: TokenId,627 ) -> u128;628}629630// Flexible enough for implementing CommonCollectionOperations631pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {632 let post_info = PostDispatchInfo {633 actual_weight: Some(weight),634 pays_fee: Pays::Yes,635 };636 match res {637 Ok(()) => Ok(post_info),638 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),639 }640}pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -2,7 +2,7 @@
use core::ops::Deref;
use frame_support::{ensure};
-use up_data_structs::{AccessMode, Collection, CollectionId, TokenId};
+use up_data_structs::{AccessMode, Collection, CollectionId, TokenId, CreateCollectionData};
use pallet_common::{
Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,
};
@@ -100,8 +100,11 @@
}
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(data)
+ pub fn init_collection(
+ owner: T::AccountId,
+ data: CreateCollectionData<T::AccountId>,
+ ) -> Result<CollectionId, DispatchError> {
+ <PalletCommon<T>>::init_collection(owner, data)
}
pub fn destroy_collection(
collection: FungibleHandle<T>,
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -2,7 +2,9 @@
use erc::ERC721Events;
use frame_support::{BoundedVec, ensure};
-use up_data_structs::{AccessMode, Collection, CollectionId, CustomDataLimit, TokenId};
+use up_data_structs::{
+ AccessMode, Collection, CollectionId, CustomDataLimit, TokenId, CreateCollectionData,
+};
use pallet_common::{
Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,
};
@@ -140,8 +142,11 @@
// unchecked calls skips any permission checks
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(data)
+ pub fn init_collection(
+ owner: T::AccountId,
+ data: CreateCollectionData<T::AccountId>,
+ ) -> Result<CollectionId, DispatchError> {
+ <PalletCommon<T>>::init_collection(owner, 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
@@ -3,6 +3,7 @@
use frame_support::{ensure, BoundedVec};
use up_data_structs::{
AccessMode, Collection, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,
+ CreateCollectionData,
};
use pallet_common::{
Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,
@@ -155,8 +156,11 @@
// unchecked calls skips any permission checks
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
- <PalletCommon<T>>::init_collection(data)
+ pub fn init_collection(
+ owner: T::AccountId,
+ data: CreateCollectionData<T::AccountId>,
+ ) -> Result<CollectionId, DispatchError> {
+ <PalletCommon<T>>::init_collection(owner, data)
}
pub fn destroy_collection(
collection: RefungibleHandle<T>,
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -36,13 +36,11 @@
use frame_system::{self as system, ensure_signed};
use sp_runtime::{sp_std::prelude::Vec};
use up_data_structs::{
- MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, CUSTOM_DATA_LIMIT,
- VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,
- FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
- NFT_SPONSOR_TRANSFER_TIMEOUT, MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH,
+ MAX_DECIMAL_POINTS, VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT,
+ OFFCHAIN_SCHEMA_LIMIT, MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH,
MAX_TOKEN_PREFIX_LENGTH, AccessMode, Collection, CreateItemData, CollectionLimits,
CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
- CustomDataLimit,
+ CreateCollectionData, CustomDataLimit,
};
use pallet_common::{
account::CrossAccountId, CollectionHandle, Pallet as PalletCommon, Error as CommonError,
@@ -84,10 +82,6 @@
ConfirmUnsetSponsorFail,
/// Length of items properties must be greater than 0.
EmptyArgument,
- /// Collection limit bounds per collection exceeded
- CollectionLimitBoundsExceeded,
- /// Tried to enable permissions which are only permitted to be disabled
- OwnerPermissionsCantBeReverted,
}
}
@@ -321,42 +315,39 @@
// returns collection ID
#[weight = <SelfWeightOf<T>>::create_collection()]
#[transactional]
+ #[deprecated]
pub fn create_collection(origin,
collection_name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,
collection_description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,
token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,
- mode: CollectionMode) -> DispatchResult {
-
- // Anyone can create a collection
- let who = ensure_signed(origin)?;
-
- // Create new collection
- let new_collection = Collection {
- owner: who,
+ mode: CollectionMode) -> DispatchResult {
+ let data: CreateCollectionData<T::AccountId> = CreateCollectionData {
name: collection_name,
- mode: mode.clone(),
- mint_mode: false,
- access: AccessMode::Normal,
description: collection_description,
token_prefix,
- offchain_schema: BoundedVec::default(),
- schema_version: SchemaVersion::ImageURL,
- sponsorship: SponsorshipState::Disabled,
- variable_on_chain_schema: BoundedVec::default(),
- const_on_chain_schema: BoundedVec::default(),
- limits: Default::default(),
- meta_update_permission: Default::default(),
+ mode,
+ ..Default::default()
};
+ Self::create_collection_ex(origin, data)
+ }
+
+ /// This method creates a collection
+ ///
+ /// Prefer it to deprecated [`created_collection`] method
+ #[weight = <SelfWeightOf<T>>::create_collection()]
+ #[transactional]
+ pub fn create_collection_ex(origin, data: CreateCollectionData<T::AccountId>) -> DispatchResult {
+ let owner = ensure_signed(origin)?;
- let _id = match mode {
- CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(new_collection)?},
+ let _id = match data.mode {
+ CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(owner, data)?},
CollectionMode::Fungible(decimal_points) => {
// check params
ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
- <PalletFungible<T>>::init_collection(new_collection)?
+ <PalletFungible<T>>::init_collection(owner, data)?
}
CollectionMode::ReFungible => {
- <PalletRefungible<T>>::init_collection(new_collection)?
+ <PalletRefungible<T>>::init_collection(owner, data)?
}
};
@@ -1093,61 +1084,12 @@
collection_id: CollectionId,
new_limit: CollectionLimits,
) -> DispatchResult {
- let mut new_limit = new_limit;
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
target_collection.check_is_owner(&sender)?;
let old_limit = &target_collection.limits;
- macro_rules! limit_default {
- ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
- $(
- if let Some($new) = $new.$field {
- let $old = $old.$field($($arg)?);
- let _ = $new;
- let _ = $old;
- $check
- } else {
- $new.$field = $old.$field
- }
- )*
- }};
- }
-
- limit_default!(old_limit, new_limit,
- account_token_ownership_limit => ensure!(
- new_limit <= MAX_TOKEN_OWNERSHIP,
- <Error<T>>::CollectionLimitBoundsExceeded,
- ),
- sponsor_transfer_timeout(match target_collection.mode {
- CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,
- CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
- CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
- }) => ensure!(
- new_limit <= MAX_SPONSOR_TIMEOUT,
- <Error<T>>::CollectionLimitBoundsExceeded,
- ),
- sponsored_data_size => ensure!(
- new_limit <= CUSTOM_DATA_LIMIT,
- <Error<T>>::CollectionLimitBoundsExceeded,
- ),
- token_limit => ensure!(
- old_limit >= new_limit && new_limit > 0,
- <CommonError<T>>::CollectionTokenLimitExceeded
- ),
- owner_can_transfer => ensure!(
- old_limit || !new_limit,
- <Error<T>>::OwnerPermissionsCantBeReverted,
- ),
- owner_can_destroy => ensure!(
- old_limit || !new_limit,
- <Error<T>>::OwnerPermissionsCantBeReverted,
- ),
- sponsored_data_rate_limit => {},
- transfers_enabled => {},
- );
-
- target_collection.limits = new_limit;
+ target_collection.limits = <PalletCommon<T>>::clamp_limits(target_collection.mode.clone(), &old_limit, new_limit)?;
<Pallet<T>>::deposit_event(Event::<T>::CollectionLimitSet(
collection_id
pallets/unique/src/tests.rsdiffbeforeafterboth--- a/pallets/unique/src/tests.rs
+++ b/pallets/unique/src/tests.rs
@@ -5,7 +5,7 @@
use up_data_structs::{
COLLECTION_NUMBER_LIMIT, CollectionId, CreateItemData, CreateFungibleData, CreateNftData,
CreateReFungibleData, MAX_DECIMAL_POINTS, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission,
- TokenId,
+ TokenId, MAX_TOKEN_OWNERSHIP,
};
use frame_support::{assert_noop, assert_ok};
use sp_std::convert::TryInto;
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -263,6 +263,31 @@
pub meta_update_permission: MetaUpdatePermission,
}
+#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative, MaxEncodedLen)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derivative(Default(bound = ""))]
+pub struct CreateCollectionData<AccountId> {
+ #[derivative(Default(value = "CollectionMode::NFT"))]
+ pub mode: CollectionMode,
+ pub access: Option<AccessMode>,
+ #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
+ pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,
+ #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
+ pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,
+ #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
+ pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,
+ #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
+ pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,
+ pub schema_version: Option<SchemaVersion>,
+ pub pending_sponsor: Option<AccountId>,
+ pub limits: Option<CollectionLimits>,
+ #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
+ pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,
+ #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]
+ pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,
+ pub meta_update_permission: Option<MetaUpdatePermission>,
+}
+
#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct NftItemType<AccountId> {
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -68,9 +68,10 @@
"testPalletPresence": "mocha --timeout 9999999 -r ts-node/register ./**/pallet-presence.test.ts",
"testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts",
"testEnableDisableTransfers": "mocha --timeout 9999999 -r ts-node/register ./**/enableDisableTransfer.test.ts",
+ "polkadot-types-fetch-metadata": "curl -H 'Content-Type: application/json' -d '{\"id\":\"1\", \"jsonrpc\":\"2.0\", \"method\": \"state_getMetadata\", \"params\":[]}' http://localhost:9933 > src/interfaces/metadata.json",
"polkadot-types-from-defs": "ts-node ./node_modules/.bin/polkadot-types-from-defs --input src/interfaces/ --package .",
- "polkadot-types-from-chain": "ts-node ./node_modules/.bin/polkadot-types-from-chain --endpoint ws://localhost:9944 --output src/interfaces/ --package .",
- "polkadot-types": "yarn polkadot-types-from-defs && yarn polkadot-types-from-chain"
+ "polkadot-types-from-chain": "ts-node ./node_modules/.bin/polkadot-types-from-chain --endpoint src/interfaces/metadata.json --output src/interfaces/ --package .",
+ "polkadot-types": "yarn polkadot-types-fetch-metadata && yarn polkadot-types-from-defs && yarn polkadot-types-from-chain"
},
"author": "",
"license": "SEE LICENSE IN ../LICENSE",
tests/src/check-event/createCollectionEvent.test.tsdiffbeforeafterboth--- a/tests/src/check-event/createCollectionEvent.test.ts
+++ b/tests/src/check-event/createCollectionEvent.test.ts
@@ -27,7 +27,7 @@
});
it('Check event from createCollection(): ', async () => {
await usingApi(async (api: ApiPromise) => {
- const tx = api.tx.unique.createCollection([0x31], [0x32], '0x33', 'NFT');
+ const tx = api.tx.unique.createCollectionEx({name: [0x31], description: [0x32], tokenPrefix: '0x33', mode: 'NFT'});
const events = await submitTransactionAsync(alice, tx);
const msg = JSON.stringify(uniqueEventMessage(events));
expect(msg).to.be.contain(checkSection);
tests/src/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -3,12 +3,11 @@
// file 'LICENSE', which is part of this source code package.
//
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import {createCollectionExpectFailure, createCollectionExpectSuccess} from './util/helpers';
+import {expect} from 'chai';
+import privateKey from './substrate/privateKey';
+import usingApi, {executeTransaction, submitTransactionAsync} from './substrate/substrate-api';
+import {createCollectionExpectFailure, createCollectionExpectSuccess, getCreateCollectionResult, getDetailedCollectionInfo} from './util/helpers';
-chai.use(chaiAsPromised);
-
describe('integration test: ext. createCollection():', () => {
it('Create new NFT collection', async () => {
await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
@@ -28,6 +27,45 @@
it('Create new ReFungible collection', async () => {
await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
});
+ it('Create new collection with extra fields', async () => {
+ await usingApi(async api => {
+ const alice = privateKey('//Alice');
+ const bob = privateKey('//Bob');
+ const tx = api.tx.unique.createCollectionEx({
+ mode: {Fungible: 8},
+ access: 'AllowList',
+ name: [1],
+ description: [2],
+ tokenPrefix: '0x000000',
+ offchainSchema: '0x111111',
+ schemaVersion: 'Unique',
+ pendingSponsor: bob.address,
+ limits: {
+ accountTokenOwnershipLimit: 3,
+ },
+ variableOnChainSchema: '0x222222',
+ constOnChainSchema: '0x333333',
+ metaUpdatePermission: 'Admin',
+ });
+ const events = await submitTransactionAsync(alice, tx);
+ const result = getCreateCollectionResult(events);
+
+ const collection = (await getDetailedCollectionInfo(api, result.collectionId))!;
+ expect(collection.owner.toString()).to.equal(alice.address);
+ expect(collection.mode.asFungible.toNumber()).to.equal(8);
+ expect(collection.access.isAllowList).to.be.true;
+ expect(collection.name.map(v => v.toNumber())).to.deep.equal([1]);
+ expect(collection.description.map(v => v.toNumber())).to.deep.equal([2]);
+ expect(collection.tokenPrefix.toString()).to.equal('0x000000');
+ expect(collection.offchainSchema.toString()).to.equal('0x111111');
+ expect(collection.schemaVersion.isUnique).to.be.true;
+ expect(collection.sponsorship.asUnconfirmed.toString()).to.equal(bob.address);
+ expect(collection.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.equal(3);
+ expect(collection.variableOnChainSchema.toString()).to.equal('0x222222');
+ expect(collection.constOnChainSchema.toString()).to.equal('0x333333');
+ expect(collection.metaUpdatePermission.isAdmin).to.be.true;
+ });
+ });
});
describe('(!negative test!) integration test: ext. createCollection():', () => {
@@ -40,4 +78,11 @@
it('(!negative test!) create new NFT collection whith incorrect data (token_prefix)', async () => {
await createCollectionExpectFailure({tokenPrefix: 'A'.repeat(17), mode: {type: 'NFT'}});
});
+ it('fails when bad limits are set', async () => {
+ await usingApi(async api => {
+ const alice = privateKey('//Alice');
+ const tx = api.tx.unique.createCollectionEx({mode: 'NFT', limits: {tokenLimit: 0}});
+ await expect(executeTransaction(api, alice, tx)).to.be.rejectedWith(/^common.CollectionTokenLimitExceeded$/);
+ });
+ });
});
tests/src/interfaces/.gitignorediffbeforeafterboth--- /dev/null
+++ b/tests/src/interfaces/.gitignore
@@ -0,0 +1 @@
+metadata.json
tests/src/interfaces/augment-api-errors.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-errors.ts
+++ b/tests/src/interfaces/augment-api-errors.ts
@@ -69,6 +69,10 @@
**/
CollectionDescriptionLimitExceeded: AugmentedError<ApiType>;
/**
+ * Collection limit bounds per collection exceeded
+ **/
+ CollectionLimitBoundsExceeded: AugmentedError<ApiType>;
+ /**
* Collection name can not be longer than 63 char.
**/
CollectionNameLimitExceeded: AugmentedError<ApiType>;
@@ -97,6 +101,10 @@
**/
NoPermission: AugmentedError<ApiType>;
/**
+ * Tried to enable permissions which are only permitted to be disabled
+ **/
+ OwnerPermissionsCantBeReverted: AugmentedError<ApiType>;
+ /**
* Collection is not in mint mode.
**/
PublicMintingNotAllowed: AugmentedError<ApiType>;
@@ -437,10 +445,6 @@
**/
CollectionDecimalPointLimitExceeded: AugmentedError<ApiType>;
/**
- * Collection limit bounds per collection exceeded
- **/
- CollectionLimitBoundsExceeded: AugmentedError<ApiType>;
- /**
* This address is not set as sponsor, use setCollectionSponsor first.
**/
ConfirmUnsetSponsorFail: AugmentedError<ApiType>;
@@ -448,10 +452,6 @@
* Length of items properties must be greater than 0.
**/
EmptyArgument: AugmentedError<ApiType>;
- /**
- * Tried to enable permissions which are only permitted to be disabled
- **/
- OwnerPermissionsCantBeReverted: AugmentedError<ApiType>;
/**
* Generic error
**/
tests/src/interfaces/augment-api-tx.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-tx.ts
+++ b/tests/src/interfaces/augment-api-tx.ts
@@ -2,7 +2,7 @@
/* eslint-disable */
import type { CumulusPrimitivesParachainInherentParachainInherentData } from './polkadot';
-import type { PalletCommonAccountBasicCrossAccountIdRepr, UpDataStructsAccessMode, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCreateItemData, UpDataStructsMetaUpdatePermission, UpDataStructsSchemaVersion } from './unique';
+import type { PalletCommonAccountBasicCrossAccountIdRepr, UpDataStructsAccessMode, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCreateCollectionData, UpDataStructsCreateItemData, UpDataStructsMetaUpdatePermission, UpDataStructsSchemaVersion } from './unique';
import type { ApiTypes, SubmittableExtrinsic } from '@polkadot/api/types';
import type { Bytes, Compact, Option, U256, Vec, bool, u128, u16, u32, u64 } from '@polkadot/types';
import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
@@ -671,6 +671,12 @@
**/
createCollection: AugmentedSubmittable<(collectionName: Vec<u16> | (u16 | AnyNumber | Uint8Array)[], collectionDescription: Vec<u16> | (u16 | AnyNumber | Uint8Array)[], tokenPrefix: Bytes | string | Uint8Array, mode: UpDataStructsCollectionMode | { NFT: any } | { Fungible: any } | { ReFungible: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Vec<u16>, Vec<u16>, Bytes, UpDataStructsCollectionMode]>;
/**
+ * This method creates a collection
+ *
+ * Prefer it to deprecated [`created_collection`] method
+ **/
+ createCollectionEx: AugmentedSubmittable<(data: UpDataStructsCreateCollectionData | { mode?: any; access?: any; name?: any; description?: any; tokenPrefix?: any; offchainSchema?: any; schemaVersion?: any; pendingSponsor?: any; limits?: any; variableOnChainSchema?: any; constOnChainSchema?: any; metaUpdatePermission?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [UpDataStructsCreateCollectionData]>;
+ /**
* This method creates a concrete instance of NFT Collection created with CreateCollection method.
*
* # Permissions
tests/src/interfaces/augment-types.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-types.ts
+++ b/tests/src/interfaces/augment-types.ts
@@ -3,7 +3,7 @@
import type { EthereumBlock, EthereumLog, EthereumReceipt, EthereumTransactionLegacyTransaction, EvmCoreErrorExitReason, FpRpcTransactionStatus } from './ethereum';
import type { CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmpQueueInboundStatus, CumulusPalletXcmpQueueOutboundStatus, CumulusPalletXcmpQueueQueueConfigData, CumulusPrimitivesParachainInherentParachainInherentData, PolkadotParachainPrimitivesXcmpMessageFormat, PolkadotPrimitivesV1AbridgedHostConfiguration, PolkadotPrimitivesV1PersistedValidationData } from './polkadot';
-import type { PalletCommonAccountBasicCrossAccountIdRepr, PalletNonfungibleItemData, PalletRefungibleItemData, PalletUnqSchedulerCallSpec, PalletUnqSchedulerReleases, PalletUnqSchedulerScheduledV2, UpDataStructsAccessMode, UpDataStructsCollection, UpDataStructsCollectionId, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCollectionStats, UpDataStructsCreateItemData, UpDataStructsMetaUpdatePermission, UpDataStructsSchemaVersion, UpDataStructsSponsorshipState, UpDataStructsTokenId } from './unique';
+import type { PalletCommonAccountBasicCrossAccountIdRepr, PalletNonfungibleItemData, PalletRefungibleItemData, PalletUnqSchedulerCallSpec, PalletUnqSchedulerReleases, PalletUnqSchedulerScheduledV2, UpDataStructsAccessMode, UpDataStructsCollection, UpDataStructsCollectionId, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCollectionStats, UpDataStructsCreateCollectionData, UpDataStructsCreateItemData, UpDataStructsMetaUpdatePermission, UpDataStructsSchemaVersion, UpDataStructsSponsorshipState, UpDataStructsTokenId } from './unique';
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';
import type { BlockAttestations, IncludedBlocks, MoreAttestations } from '@polkadot/types/interfaces/attestations';
@@ -1021,6 +1021,7 @@
UpDataStructsCollectionLimits: UpDataStructsCollectionLimits;
UpDataStructsCollectionMode: UpDataStructsCollectionMode;
UpDataStructsCollectionStats: UpDataStructsCollectionStats;
+ UpDataStructsCreateCollectionData: UpDataStructsCreateCollectionData;
UpDataStructsCreateItemData: UpDataStructsCreateItemData;
UpDataStructsMetaUpdatePermission: UpDataStructsMetaUpdatePermission;
UpDataStructsSchemaVersion: UpDataStructsSchemaVersion;
tests/src/interfaces/unique/definitions.tsdiffbeforeafterboth--- a/tests/src/interfaces/unique/definitions.ts
+++ b/tests/src/interfaces/unique/definitions.ts
@@ -67,6 +67,20 @@
constOnChainSchema: 'Vec<u8>',
metaUpdatePermission: 'UpDataStructsMetaUpdatePermission',
},
+ UpDataStructsCreateCollectionData: {
+ mode: 'UpDataStructsCollectionMode',
+ access: 'Option<UpDataStructsAccessMode>',
+ name: 'Vec<u16>',
+ description: 'Vec<u16>',
+ tokenPrefix: 'Vec<u8>',
+ offchainSchema: 'Vec<u8>',
+ schemaVersion: 'Option<UpDataStructsSchemaVersion>',
+ pendingSponsor: 'Option<AccountId>',
+ limits: 'Option<UpDataStructsCollectionLimits>',
+ variableOnChainSchema: 'Vec<u8>',
+ constOnChainSchema: 'Vec<u8>',
+ metaUpdatePermission: 'Option<UpDataStructsMetaUpdatePermission>',
+ },
UpDataStructsCollectionStats: {
created: 'u32',
destroyed: 'u32',
@@ -76,7 +90,13 @@
UpDataStructsTokenId: 'u32',
PalletNonfungibleItemData: mkDummy('NftItemData'),
PalletRefungibleItemData: mkDummy('RftItemData'),
- UpDataStructsCollectionMode: mkDummy('CollectionMode'),
+ UpDataStructsCollectionMode: {
+ _enum: {
+ NFT: null,
+ Fungible: 'u32',
+ ReFungible: null,
+ },
+ },
UpDataStructsCreateItemData: mkDummy('CreateItemData'),
UpDataStructsCollectionLimits: {
accountTokenOwnershipLimit: 'Option<u32>',
@@ -101,7 +121,9 @@
UpDataStructsAccessMode: {
_enum: ['Normal', 'AllowList'],
},
- UpDataStructsSchemaVersion: mkDummy('SchemaVersion'),
+ UpDataStructsSchemaVersion: {
+ _enum: ['ImageURL', 'Unique'],
+ },
PalletUnqSchedulerScheduledV2: mkDummy('ScheduledV2'),
PalletUnqSchedulerCallSpec: mkDummy('CallSpec'),
tests/src/interfaces/unique/types.tsdiffbeforeafterboth--- a/tests/src/interfaces/unique/types.ts
+++ b/tests/src/interfaces/unique/types.ts
@@ -77,8 +77,11 @@
}
/** @name UpDataStructsCollectionMode */
-export interface UpDataStructsCollectionMode extends Struct {
- readonly dummyCollectionMode: u32;
+export interface UpDataStructsCollectionMode extends Enum {
+ readonly isNft: boolean;
+ readonly isFungible: boolean;
+ readonly asFungible: u32;
+ readonly isReFungible: boolean;
}
/** @name UpDataStructsCollectionStats */
@@ -88,6 +91,22 @@
readonly alive: u32;
}
+/** @name UpDataStructsCreateCollectionData */
+export interface UpDataStructsCreateCollectionData extends Struct {
+ readonly mode: UpDataStructsCollectionMode;
+ readonly access: Option<UpDataStructsAccessMode>;
+ readonly name: Vec<u16>;
+ readonly description: Vec<u16>;
+ readonly tokenPrefix: Bytes;
+ readonly offchainSchema: Bytes;
+ readonly schemaVersion: Option<UpDataStructsSchemaVersion>;
+ readonly pendingSponsor: Option<AccountId>;
+ readonly limits: Option<UpDataStructsCollectionLimits>;
+ readonly variableOnChainSchema: Bytes;
+ readonly constOnChainSchema: Bytes;
+ readonly metaUpdatePermission: Option<UpDataStructsMetaUpdatePermission>;
+}
+
/** @name UpDataStructsCreateItemData */
export interface UpDataStructsCreateItemData extends Struct {
readonly dummyCreateItemData: u32;
@@ -101,8 +120,9 @@
}
/** @name UpDataStructsSchemaVersion */
-export interface UpDataStructsSchemaVersion extends Struct {
- readonly dummySchemaVersion: u32;
+export interface UpDataStructsSchemaVersion extends Enum {
+ readonly isImageUrl: boolean;
+ readonly isUnique: boolean;
}
/** @name UpDataStructsSponsorshipState */
tests/src/substrate/substrate-api.tsdiffbeforeafterboth--- a/tests/src/substrate/substrate-api.ts
+++ b/tests/src/substrate/substrate-api.ts
@@ -95,6 +95,32 @@
return TransactionStatus.Fail;
}
+export function executeTransaction(api: ApiPromise, sender: IKeyringPair, transaction: SubmittableExtrinsic<'promise'>): Promise<EventRecord[]> {
+ return new Promise(async (res, rej) => {
+ try {
+ await transaction.signAndSend(sender, ({events, status}) => {
+ if (!status.isInBlock && !status.isFinalized) return;
+ for (const {event} of events) {
+ if (api.events.system.ExtrinsicSuccess.is(event)) {
+ res(events);
+ } else if (api.events.system.ExtrinsicFailed.is(event)) {
+ const {data: [error]} = event;
+ if (error.isModule) {
+ const decoded = api.registry.findMetaError(error.asModule);
+ const {method, section} = decoded;
+ rej(new Error(`${section}.${method}`));
+ } else {
+ rej(new Error(error.toString()));
+ }
+ }
+ }
+ });
+ } catch (e) {
+ rej(e);
+ }
+ });
+}
+
export function
submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {
/* eslint no-async-promise-executor: "off" */
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -49,7 +49,7 @@
};
} else if ('Substrate' in input) {
return input;
- }else if ('substrate' in input) {
+ } else if ('substrate' in input) {
return {
Substrate: (input as any).substrate,
};
@@ -116,15 +116,15 @@
export interface IChainLimits {
collectionNumbersLimit: number;
- accountTokenOwnershipLimit: number;
- collectionsAdminsLimit: number;
- customDataLimit: number;
- nftSponsorTransferTimeout: number;
- fungibleSponsorTransferTimeout: number;
- refungibleSponsorTransferTimeout: number;
- offchainSchemaLimit: number;
- variableOnChainSchemaLimit: number;
- constOnChainSchemaLimit: number;
+ accountTokenOwnershipLimit: number;
+ collectionsAdminsLimit: number;
+ customDataLimit: number;
+ nftSponsorTransferTimeout: number;
+ fungibleSponsorTransferTimeout: number;
+ refungibleSponsorTransferTimeout: number;
+ offchainSchemaLimit: number;
+ variableOnChainSchemaLimit: number;
+ constOnChainSchemaLimit: number;
}
export interface IReFungibleTokenDataType {
@@ -283,7 +283,7 @@
modeprm = {refungible: null};
}
- const tx = api.tx.unique.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);
+ const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});
const events = await submitTransactionAsync(alicePrivateKey, tx);
const result = getCreateCollectionResult(events);
@@ -329,7 +329,7 @@
// Run the CreateCollection transaction
const alicePrivateKey = privateKey('//Alice');
- const tx = api.tx.unique.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);
+ const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});
const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;
const result = getCreateCollectionResult(events);
@@ -557,7 +557,7 @@
await usingApi(async (api) => {
- const tx = api.tx.unique.setTransfersEnabledFlag (collectionId, enabled);
+ const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);
const events = await submitTransactionAsync(sender, tx);
const result = getGenericResult(events);
@@ -569,7 +569,7 @@
await usingApi(async (api) => {
- const tx = api.tx.unique.setTransfersEnabledFlag (collectionId, enabled);
+ const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);
const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
const result = getGenericResult(events);
@@ -811,8 +811,7 @@
}
export async function
-getFreeBalance(account: IKeyringPair) : Promise<bigint>
-{
+getFreeBalance(account: IKeyringPair): Promise<bigint> {
let balance = 0n;
await usingApi(async (api) => {
balance = BigInt((await api.query.system.account(account.address)).data.free.toString());