difftreelog
Merge pull request #277 from UniqueNetwork/feature/create-collection-ex
in: master
Add createCollectionEx call
18 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -14,7 +14,10 @@
use up_data_structs::{
COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,
MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo,
- TokenId, Weight, WithdrawReasons, CollectionStats, CustomDataLimit,
+ TokenId, Weight, WithdrawReasons, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode,
+ NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+ REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,
+ CustomDataLimit, CreateCollectionData, SponsorshipState,
};
pub use pallet::*;
use sp_core::H160;
@@ -285,6 +288,10 @@
TokenVariableDataLimitExceeded,
/// Exceeded max admin count
CollectionAdminCountExceeded,
+ /// Collection limit bounds per collection exceeded
+ CollectionLimitBoundsExceeded,
+ /// Tried to enable permissions which are only permitted to be disabled
+ OwnerPermissionsCantBeReverted,
/// Collection settings not allowing items transferring
TransferNotAllowed,
@@ -395,7 +402,10 @@
}
impl<T: Config> Pallet<T> {
- pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {
+ pub fn init_collection(
+ owner: T::AccountId,
+ data: CreateCollectionData<T::AccountId>,
+ ) -> Result<CollectionId, DispatchError> {
{
ensure!(
data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,
@@ -418,6 +428,29 @@
// =========
+ let collection = Collection {
+ owner: owner.clone(),
+ name: data.name,
+ mode: data.mode.clone(),
+ mint_mode: false,
+ access: data.access.unwrap_or_default(),
+ description: data.description,
+ token_prefix: data.token_prefix,
+ offchain_schema: data.offchain_schema,
+ schema_version: data.schema_version.unwrap_or_default(),
+ sponsorship: data
+ .pending_sponsor
+ .map(SponsorshipState::Unconfirmed)
+ .unwrap_or_default(),
+ variable_on_chain_schema: data.variable_on_chain_schema,
+ const_on_chain_schema: data.const_on_chain_schema,
+ limits: data
+ .limits
+ .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))
+ .unwrap_or_else(|| Ok(CollectionLimits::default()))?,
+ meta_update_permission: data.meta_update_permission.unwrap_or_default(),
+ };
+
// Take a (non-refundable) deposit of collection creation
{
let mut imbalance =
@@ -429,7 +462,7 @@
),
);
<T as Config>::Currency::settle(
- &data.owner,
+ &owner,
imbalance,
WithdrawReasons::TRANSFER,
ExistenceRequirement::KeepAlive,
@@ -438,12 +471,8 @@
}
<CreatedCollectionCount<T>>::put(created_count);
- <Pallet<T>>::deposit_event(Event::CollectionCreated(
- id,
- data.mode.id(),
- data.owner.clone(),
- ));
- <CollectionById<T>>::insert(id, data);
+ <Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));
+ <CollectionById<T>>::insert(id, collection);
Ok(id)
}
@@ -527,6 +556,61 @@
Ok(())
}
+
+ pub fn clamp_limits(
+ mode: CollectionMode,
+ old_limit: &CollectionLimits,
+ mut new_limit: CollectionLimits,
+ ) -> Result<CollectionLimits, DispatchError> {
+ 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 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,
+ <Error<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 => {},
+ );
+ Ok(new_limit)
+ }
}
#[macro_export]
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.rsdiffbeforeafterboth1#![cfg_attr(not(feature = "std"), no_std)]23use frame_support::{ensure, BoundedVec};4use up_data_structs::{5 AccessMode, Collection, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,6};7use pallet_common::{8 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,9};10use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};11use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};12use core::ops::Deref;13use codec::{Encode, Decode, MaxEncodedLen};14use scale_info::TypeInfo;1516pub use pallet::*;17#[cfg(feature = "runtime-benchmarks")]18pub mod benchmarking;19pub mod common;20pub mod erc;21pub mod weights;22pub struct CreateItemData<T: Config> {23 pub const_data: BoundedVec<u8, CustomDataLimit>,24 pub variable_data: BoundedVec<u8, CustomDataLimit>,25 pub users: BTreeMap<T::CrossAccountId, u128>,26}27pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2829#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]30pub struct ItemData {31 pub const_data: BoundedVec<u8, CustomDataLimit>,32 pub variable_data: BoundedVec<u8, CustomDataLimit>,33}3435#[frame_support::pallet]36pub mod pallet {37 use super::*;38 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};39 use up_data_structs::{CollectionId, TokenId};40 use super::weights::WeightInfo;4142 #[pallet::error]43 pub enum Error<T> {44 /// Not Refungible item data used to mint in Refungible collection.45 NotRefungibleDataUsedToMintFungibleCollectionToken,46 /// Maximum refungibility exceeded47 WrongRefungiblePieces,48 }4950 #[pallet::config]51 pub trait Config: frame_system::Config + pallet_common::Config {52 type WeightInfo: WeightInfo;53 }5455 #[pallet::pallet]56 #[pallet::generate_store(pub(super) trait Store)]57 pub struct Pallet<T>(_);5859 #[pallet::storage]60 pub type TokensMinted<T: Config> =61 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;62 #[pallet::storage]63 pub type TokensBurnt<T: Config> =64 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6566 #[pallet::storage]67 pub type TokenData<T: Config> = StorageNMap<68 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),69 Value = ItemData,70 QueryKind = ValueQuery,71 >;7273 #[pallet::storage]74 pub type TotalSupply<T: Config> = StorageNMap<75 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),76 Value = u128,77 QueryKind = ValueQuery,78 >;7980 /// Used to enumerate tokens owned by account81 #[pallet::storage]82 pub type Owned<T: Config> = StorageNMap<83 Key = (84 Key<Twox64Concat, CollectionId>,85 Key<Blake2_128Concat, T::CrossAccountId>,86 Key<Twox64Concat, TokenId>,87 ),88 Value = bool,89 QueryKind = ValueQuery,90 >;9192 #[pallet::storage]93 pub type AccountBalance<T: Config> = StorageNMap<94 Key = (95 Key<Twox64Concat, CollectionId>,96 // Owner97 Key<Blake2_128Concat, T::CrossAccountId>,98 ),99 Value = u32,100 QueryKind = ValueQuery,101 >;102103 #[pallet::storage]104 pub type Balance<T: Config> = StorageNMap<105 Key = (106 Key<Twox64Concat, CollectionId>,107 Key<Twox64Concat, TokenId>,108 // Owner109 Key<Blake2_128Concat, T::CrossAccountId>,110 ),111 Value = u128,112 QueryKind = ValueQuery,113 >;114115 #[pallet::storage]116 pub type Allowance<T: Config> = StorageNMap<117 Key = (118 Key<Twox64Concat, CollectionId>,119 Key<Twox64Concat, TokenId>,120 // Owner121 Key<Blake2_128, T::CrossAccountId>,122 // Spender123 Key<Blake2_128Concat, T::CrossAccountId>,124 ),125 Value = u128,126 QueryKind = ValueQuery,127 >;128}129130pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);131impl<T: Config> RefungibleHandle<T> {132 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {133 Self(inner)134 }135 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {136 self.0137 }138}139impl<T: Config> Deref for RefungibleHandle<T> {140 type Target = pallet_common::CollectionHandle<T>;141142 fn deref(&self) -> &Self::Target {143 &self.0144 }145}146147impl<T: Config> Pallet<T> {148 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {149 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)150 }151 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {152 <TotalSupply<T>>::contains_key((collection.id, token))153 }154}155156// unchecked calls skips any permission checks157impl<T: Config> Pallet<T> {158 pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {159 <PalletCommon<T>>::init_collection(data)160 }161 pub fn destroy_collection(162 collection: RefungibleHandle<T>,163 sender: &T::CrossAccountId,164 ) -> DispatchResult {165 let id = collection.id;166167 // =========168169 PalletCommon::destroy_collection(collection.0, sender)?;170171 <TokensMinted<T>>::remove(id);172 <TokensBurnt<T>>::remove(id);173 <TokenData<T>>::remove_prefix((id,), None);174 <TotalSupply<T>>::remove_prefix((id,), None);175 <Balance<T>>::remove_prefix((id,), None);176 <Allowance<T>>::remove_prefix((id,), None);177 <Owned<T>>::remove_prefix((id,), None);178 <AccountBalance<T>>::remove_prefix((id,), None);179 Ok(())180 }181182 pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {183 let burnt = <TokensBurnt<T>>::get(collection.id)184 .checked_add(1)185 .ok_or(ArithmeticError::Overflow)?;186187 <TokensBurnt<T>>::insert(collection.id, burnt);188 <TokenData<T>>::remove((collection.id, token_id));189 <TotalSupply<T>>::remove((collection.id, token_id));190 <Balance<T>>::remove_prefix((collection.id, token_id), None);191 <Allowance<T>>::remove_prefix((collection.id, token_id), None);192 // TODO: ERC721 transfer event193 Ok(())194 }195196 pub fn burn(197 collection: &RefungibleHandle<T>,198 owner: &T::CrossAccountId,199 token: TokenId,200 amount: u128,201 ) -> DispatchResult {202 let total_supply = <TotalSupply<T>>::get((collection.id, token))203 .checked_sub(amount)204 .ok_or(<CommonError<T>>::TokenValueTooLow)?;205206 // This was probally last owner of this token?207 if total_supply == 0 {208 // Ensure user actually owns this amount209 ensure!(210 <Balance<T>>::get((collection.id, token, owner)) == amount,211 <CommonError<T>>::TokenValueTooLow212 );213 let account_balance = <AccountBalance<T>>::get((collection.id, owner))214 .checked_sub(1)215 // Should not occur216 .ok_or(ArithmeticError::Underflow)?;217218 // =========219220 <Owned<T>>::remove((collection.id, owner, token));221 <AccountBalance<T>>::insert((collection.id, owner), account_balance);222 Self::burn_token(collection, token)?;223 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(224 collection.id,225 token,226 owner.clone(),227 amount,228 ));229 return Ok(());230 }231232 let balance = <Balance<T>>::get((collection.id, token, owner))233 .checked_sub(amount)234 .ok_or(<CommonError<T>>::TokenValueTooLow)?;235 let account_balance = if balance == 0 {236 <AccountBalance<T>>::get((collection.id, owner))237 .checked_sub(1)238 // Should not occur239 .ok_or(ArithmeticError::Underflow)?240 } else {241 0242 };243244 // =========245246 if balance == 0 {247 <Owned<T>>::remove((collection.id, owner, token));248 <Balance<T>>::remove((collection.id, token, owner));249 <AccountBalance<T>>::insert((collection.id, owner), account_balance);250 } else {251 <Balance<T>>::insert((collection.id, token, owner), balance);252 }253 <TotalSupply<T>>::insert((collection.id, token), total_supply);254 // TODO: ERC20 transfer event255 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(256 collection.id,257 token,258 owner.clone(),259 amount,260 ));261 Ok(())262 }263264 pub fn transfer(265 collection: &RefungibleHandle<T>,266 from: &T::CrossAccountId,267 to: &T::CrossAccountId,268 token: TokenId,269 amount: u128,270 ) -> DispatchResult {271 ensure!(272 collection.limits.transfers_enabled(),273 <CommonError<T>>::TransferNotAllowed274 );275276 if collection.access == AccessMode::AllowList {277 collection.check_allowlist(from)?;278 collection.check_allowlist(to)?;279 }280 <PalletCommon<T>>::ensure_correct_receiver(to)?;281282 let balance_from = <Balance<T>>::get((collection.id, token, from))283 .checked_sub(amount)284 .ok_or(<CommonError<T>>::TokenValueTooLow)?;285 let mut create_target = false;286 let from_to_differ = from != to;287 let balance_to = if from != to {288 let old_balance = <Balance<T>>::get((collection.id, token, to));289 if old_balance == 0 {290 create_target = true;291 }292 Some(293 old_balance294 .checked_add(amount)295 .ok_or(ArithmeticError::Overflow)?,296 )297 } else {298 None299 };300301 let account_balance_from = if balance_from == 0 {302 Some(303 <AccountBalance<T>>::get((collection.id, from))304 .checked_sub(1)305 // Should not occur306 .ok_or(ArithmeticError::Underflow)?,307 )308 } else {309 None310 };311 // Account data is created in token, AccountBalance should be increased312 // But only if from != to as we shouldn't check overflow in this case313 let account_balance_to = if create_target && from_to_differ {314 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))315 .checked_add(1)316 .ok_or(ArithmeticError::Overflow)?;317 ensure!(318 account_balance_to < collection.limits.account_token_ownership_limit(),319 <CommonError<T>>::AccountTokenLimitExceeded,320 );321322 Some(account_balance_to)323 } else {324 None325 };326327 // =========328329 if let Some(balance_to) = balance_to {330 // from != to331 if balance_from == 0 {332 <Balance<T>>::remove((collection.id, token, from));333 } else {334 <Balance<T>>::insert((collection.id, token, from), balance_from);335 }336 <Balance<T>>::insert((collection.id, token, to), balance_to);337 if let Some(account_balance_from) = account_balance_from {338 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);339 <Owned<T>>::remove((collection.id, from, token));340 }341 if let Some(account_balance_to) = account_balance_to {342 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);343 <Owned<T>>::insert((collection.id, to, token), true);344 }345 }346347 // TODO: ERC20 transfer event348 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(349 collection.id,350 token,351 from.clone(),352 to.clone(),353 amount,354 ));355 Ok(())356 }357358 pub fn create_multiple_items(359 collection: &RefungibleHandle<T>,360 sender: &T::CrossAccountId,361 data: Vec<CreateItemData<T>>,362 ) -> DispatchResult {363 if !collection.is_owner_or_admin(sender) {364 ensure!(365 collection.mint_mode,366 <CommonError<T>>::PublicMintingNotAllowed367 );368 collection.check_allowlist(sender)?;369370 for item in data.iter() {371 for user in item.users.keys() {372 collection.check_allowlist(user)?;373 }374 }375 }376377 for item in data.iter() {378 for (owner, _) in item.users.iter() {379 <PalletCommon<T>>::ensure_correct_receiver(owner)?;380 }381 }382383 // Total pieces per tokens384 let totals = data385 .iter()386 .map(|data| {387 Ok(data388 .users389 .iter()390 .map(|u| u.1)391 .try_fold(0u128, |acc, v| acc.checked_add(*v))392 .ok_or(ArithmeticError::Overflow)?)393 })394 .collect::<Result<Vec<_>, DispatchError>>()?;395 for total in &totals {396 ensure!(397 *total <= MAX_REFUNGIBLE_PIECES,398 <Error<T>>::WrongRefungiblePieces399 );400 }401402 let first_token_id = <TokensMinted<T>>::get(collection.id);403 let tokens_minted = first_token_id404 .checked_add(data.len() as u32)405 .ok_or(ArithmeticError::Overflow)?;406 ensure!(407 tokens_minted < collection.limits.token_limit(),408 <CommonError<T>>::CollectionTokenLimitExceeded409 );410411 let mut balances = BTreeMap::new();412 for data in &data {413 for owner in data.users.keys() {414 let balance = balances415 .entry(owner)416 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));417 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;418419 ensure!(420 *balance <= collection.limits.account_token_ownership_limit(),421 <CommonError<T>>::AccountTokenLimitExceeded,422 );423 }424 }425426 // =========427428 <TokensMinted<T>>::insert(collection.id, tokens_minted);429 for (account, balance) in balances {430 <AccountBalance<T>>::insert((collection.id, account), balance);431 }432 for (i, token) in data.into_iter().enumerate() {433 let token_id = first_token_id + i as u32 + 1;434 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);435436 <TokenData<T>>::insert(437 (collection.id, token_id),438 ItemData {439 const_data: token.const_data,440 variable_data: token.variable_data,441 },442 );443 for (user, amount) in token.users.into_iter() {444 if amount == 0 {445 continue;446 }447 <Balance<T>>::insert((collection.id, token_id, &user), amount);448 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);449 // TODO: ERC20 transfer event450 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(451 collection.id,452 TokenId(token_id),453 user,454 amount,455 ));456 }457 }458 Ok(())459 }460461 pub fn set_allowance_unchecked(462 collection: &RefungibleHandle<T>,463 sender: &T::CrossAccountId,464 spender: &T::CrossAccountId,465 token: TokenId,466 amount: u128,467 ) {468 if amount == 0 {469 <Allowance<T>>::remove((collection.id, token, sender, spender));470 } else {471 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);472 }473 // TODO: ERC20 approval event474 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(475 collection.id,476 token,477 sender.clone(),478 spender.clone(),479 amount,480 ))481 }482483 pub fn set_allowance(484 collection: &RefungibleHandle<T>,485 sender: &T::CrossAccountId,486 spender: &T::CrossAccountId,487 token: TokenId,488 amount: u128,489 ) -> DispatchResult {490 if collection.access == AccessMode::AllowList {491 collection.check_allowlist(sender)?;492 collection.check_allowlist(spender)?;493 }494495 <PalletCommon<T>>::ensure_correct_receiver(spender)?;496497 if <Balance<T>>::get((collection.id, token, sender)) < amount {498 ensure!(499 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),500 <CommonError<T>>::CantApproveMoreThanOwned501 );502 }503504 // =========505506 Self::set_allowance_unchecked(collection, sender, spender, token, amount);507 Ok(())508 }509510 pub fn transfer_from(511 collection: &RefungibleHandle<T>,512 spender: &T::CrossAccountId,513 from: &T::CrossAccountId,514 to: &T::CrossAccountId,515 token: TokenId,516 amount: u128,517 ) -> DispatchResult {518 if spender.conv_eq(from) {519 return Self::transfer(collection, from, to, token, amount);520 }521 if collection.access == AccessMode::AllowList {522 // `from`, `to` checked in [`transfer`]523 collection.check_allowlist(spender)?;524 }525526 let allowance =527 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);528 if allowance.is_none() {529 ensure!(530 collection.ignores_allowance(spender),531 <CommonError<T>>::TokenValueNotEnough532 );533 }534535 // =========536537 Self::transfer(collection, from, to, token, amount)?;538 if let Some(allowance) = allowance {539 Self::set_allowance_unchecked(collection, from, spender, token, allowance);540 }541 Ok(())542 }543544 pub fn burn_from(545 collection: &RefungibleHandle<T>,546 spender: &T::CrossAccountId,547 from: &T::CrossAccountId,548 token: TokenId,549 amount: u128,550 ) -> DispatchResult {551 if spender.conv_eq(from) {552 return Self::burn(collection, from, token, amount);553 }554 if collection.access == AccessMode::AllowList {555 // `from` checked in [`burn`]556 collection.check_allowlist(spender)?;557 }558559 let allowance =560 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);561 if allowance.is_none() {562 ensure!(563 collection.ignores_allowance(spender),564 <CommonError<T>>::TokenValueNotEnough565 );566 }567568 // =========569570 Self::burn(collection, from, token, amount)?;571 if let Some(allowance) = allowance {572 Self::set_allowance_unchecked(collection, from, spender, token, allowance);573 }574 Ok(())575 }576577 pub fn set_variable_metadata(578 collection: &RefungibleHandle<T>,579 sender: &T::CrossAccountId,580 token: TokenId,581 data: BoundedVec<u8, CustomDataLimit>,582 ) -> DispatchResult {583 collection.check_can_update_meta(584 sender,585 &T::CrossAccountId::from_sub(collection.owner.clone()),586 )?;587588 let token_data = <TokenData<T>>::get((collection.id, token));589590 // =========591592 <TokenData<T>>::insert(593 (collection.id, token),594 ItemData {595 variable_data: data,596 ..token_data597 },598 );599 Ok(())600 }601602 /// Delegated to `create_multiple_items`603 pub fn create_item(604 collection: &RefungibleHandle<T>,605 sender: &T::CrossAccountId,606 data: CreateItemData<T>,607 ) -> DispatchResult {608 Self::create_multiple_items(collection, sender, vec![data])609 }610}1#![cfg_attr(not(feature = "std"), no_std)]23use frame_support::{ensure, BoundedVec};4use up_data_structs::{5 AccessMode, Collection, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,6 CreateCollectionData,7};8use pallet_common::{9 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,10};11use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};12use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};13use core::ops::Deref;14use codec::{Encode, Decode, MaxEncodedLen};15use scale_info::TypeInfo;1617pub use pallet::*;18#[cfg(feature = "runtime-benchmarks")]19pub mod benchmarking;20pub mod common;21pub mod erc;22pub mod weights;23pub struct CreateItemData<T: Config> {24 pub const_data: BoundedVec<u8, CustomDataLimit>,25 pub variable_data: BoundedVec<u8, CustomDataLimit>,26 pub users: BTreeMap<T::CrossAccountId, u128>,27}28pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2930#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]31pub struct ItemData {32 pub const_data: BoundedVec<u8, CustomDataLimit>,33 pub variable_data: BoundedVec<u8, CustomDataLimit>,34}3536#[frame_support::pallet]37pub mod pallet {38 use super::*;39 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};40 use up_data_structs::{CollectionId, TokenId};41 use super::weights::WeightInfo;4243 #[pallet::error]44 pub enum Error<T> {45 /// Not Refungible item data used to mint in Refungible collection.46 NotRefungibleDataUsedToMintFungibleCollectionToken,47 /// Maximum refungibility exceeded48 WrongRefungiblePieces,49 }5051 #[pallet::config]52 pub trait Config: frame_system::Config + pallet_common::Config {53 type WeightInfo: WeightInfo;54 }5556 #[pallet::pallet]57 #[pallet::generate_store(pub(super) trait Store)]58 pub struct Pallet<T>(_);5960 #[pallet::storage]61 pub type TokensMinted<T: Config> =62 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;63 #[pallet::storage]64 pub type TokensBurnt<T: Config> =65 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6667 #[pallet::storage]68 pub type TokenData<T: Config> = StorageNMap<69 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),70 Value = ItemData,71 QueryKind = ValueQuery,72 >;7374 #[pallet::storage]75 pub type TotalSupply<T: Config> = StorageNMap<76 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),77 Value = u128,78 QueryKind = ValueQuery,79 >;8081 /// Used to enumerate tokens owned by account82 #[pallet::storage]83 pub type Owned<T: Config> = StorageNMap<84 Key = (85 Key<Twox64Concat, CollectionId>,86 Key<Blake2_128Concat, T::CrossAccountId>,87 Key<Twox64Concat, TokenId>,88 ),89 Value = bool,90 QueryKind = ValueQuery,91 >;9293 #[pallet::storage]94 pub type AccountBalance<T: Config> = StorageNMap<95 Key = (96 Key<Twox64Concat, CollectionId>,97 // Owner98 Key<Blake2_128Concat, T::CrossAccountId>,99 ),100 Value = u32,101 QueryKind = ValueQuery,102 >;103104 #[pallet::storage]105 pub type Balance<T: Config> = StorageNMap<106 Key = (107 Key<Twox64Concat, CollectionId>,108 Key<Twox64Concat, TokenId>,109 // Owner110 Key<Blake2_128Concat, T::CrossAccountId>,111 ),112 Value = u128,113 QueryKind = ValueQuery,114 >;115116 #[pallet::storage]117 pub type Allowance<T: Config> = StorageNMap<118 Key = (119 Key<Twox64Concat, CollectionId>,120 Key<Twox64Concat, TokenId>,121 // Owner122 Key<Blake2_128, T::CrossAccountId>,123 // Spender124 Key<Blake2_128Concat, T::CrossAccountId>,125 ),126 Value = u128,127 QueryKind = ValueQuery,128 >;129}130131pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);132impl<T: Config> RefungibleHandle<T> {133 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {134 Self(inner)135 }136 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {137 self.0138 }139}140impl<T: Config> Deref for RefungibleHandle<T> {141 type Target = pallet_common::CollectionHandle<T>;142143 fn deref(&self) -> &Self::Target {144 &self.0145 }146}147148impl<T: Config> Pallet<T> {149 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {150 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)151 }152 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {153 <TotalSupply<T>>::contains_key((collection.id, token))154 }155}156157// unchecked calls skips any permission checks158impl<T: Config> Pallet<T> {159 pub fn init_collection(160 owner: T::AccountId,161 data: CreateCollectionData<T::AccountId>,162 ) -> Result<CollectionId, DispatchError> {163 <PalletCommon<T>>::init_collection(owner, data)164 }165 pub fn destroy_collection(166 collection: RefungibleHandle<T>,167 sender: &T::CrossAccountId,168 ) -> DispatchResult {169 let id = collection.id;170171 // =========172173 PalletCommon::destroy_collection(collection.0, sender)?;174175 <TokensMinted<T>>::remove(id);176 <TokensBurnt<T>>::remove(id);177 <TokenData<T>>::remove_prefix((id,), None);178 <TotalSupply<T>>::remove_prefix((id,), None);179 <Balance<T>>::remove_prefix((id,), None);180 <Allowance<T>>::remove_prefix((id,), None);181 <Owned<T>>::remove_prefix((id,), None);182 <AccountBalance<T>>::remove_prefix((id,), None);183 Ok(())184 }185186 pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {187 let burnt = <TokensBurnt<T>>::get(collection.id)188 .checked_add(1)189 .ok_or(ArithmeticError::Overflow)?;190191 <TokensBurnt<T>>::insert(collection.id, burnt);192 <TokenData<T>>::remove((collection.id, token_id));193 <TotalSupply<T>>::remove((collection.id, token_id));194 <Balance<T>>::remove_prefix((collection.id, token_id), None);195 <Allowance<T>>::remove_prefix((collection.id, token_id), None);196 // TODO: ERC721 transfer event197 Ok(())198 }199200 pub fn burn(201 collection: &RefungibleHandle<T>,202 owner: &T::CrossAccountId,203 token: TokenId,204 amount: u128,205 ) -> DispatchResult {206 let total_supply = <TotalSupply<T>>::get((collection.id, token))207 .checked_sub(amount)208 .ok_or(<CommonError<T>>::TokenValueTooLow)?;209210 // This was probally last owner of this token?211 if total_supply == 0 {212 // Ensure user actually owns this amount213 ensure!(214 <Balance<T>>::get((collection.id, token, owner)) == amount,215 <CommonError<T>>::TokenValueTooLow216 );217 let account_balance = <AccountBalance<T>>::get((collection.id, owner))218 .checked_sub(1)219 // Should not occur220 .ok_or(ArithmeticError::Underflow)?;221222 // =========223224 <Owned<T>>::remove((collection.id, owner, token));225 <AccountBalance<T>>::insert((collection.id, owner), account_balance);226 Self::burn_token(collection, token)?;227 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(228 collection.id,229 token,230 owner.clone(),231 amount,232 ));233 return Ok(());234 }235236 let balance = <Balance<T>>::get((collection.id, token, owner))237 .checked_sub(amount)238 .ok_or(<CommonError<T>>::TokenValueTooLow)?;239 let account_balance = if balance == 0 {240 <AccountBalance<T>>::get((collection.id, owner))241 .checked_sub(1)242 // Should not occur243 .ok_or(ArithmeticError::Underflow)?244 } else {245 0246 };247248 // =========249250 if balance == 0 {251 <Owned<T>>::remove((collection.id, owner, token));252 <Balance<T>>::remove((collection.id, token, owner));253 <AccountBalance<T>>::insert((collection.id, owner), account_balance);254 } else {255 <Balance<T>>::insert((collection.id, token, owner), balance);256 }257 <TotalSupply<T>>::insert((collection.id, token), total_supply);258 // TODO: ERC20 transfer event259 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(260 collection.id,261 token,262 owner.clone(),263 amount,264 ));265 Ok(())266 }267268 pub fn transfer(269 collection: &RefungibleHandle<T>,270 from: &T::CrossAccountId,271 to: &T::CrossAccountId,272 token: TokenId,273 amount: u128,274 ) -> DispatchResult {275 ensure!(276 collection.limits.transfers_enabled(),277 <CommonError<T>>::TransferNotAllowed278 );279280 if collection.access == AccessMode::AllowList {281 collection.check_allowlist(from)?;282 collection.check_allowlist(to)?;283 }284 <PalletCommon<T>>::ensure_correct_receiver(to)?;285286 let balance_from = <Balance<T>>::get((collection.id, token, from))287 .checked_sub(amount)288 .ok_or(<CommonError<T>>::TokenValueTooLow)?;289 let mut create_target = false;290 let from_to_differ = from != to;291 let balance_to = if from != to {292 let old_balance = <Balance<T>>::get((collection.id, token, to));293 if old_balance == 0 {294 create_target = true;295 }296 Some(297 old_balance298 .checked_add(amount)299 .ok_or(ArithmeticError::Overflow)?,300 )301 } else {302 None303 };304305 let account_balance_from = if balance_from == 0 {306 Some(307 <AccountBalance<T>>::get((collection.id, from))308 .checked_sub(1)309 // Should not occur310 .ok_or(ArithmeticError::Underflow)?,311 )312 } else {313 None314 };315 // Account data is created in token, AccountBalance should be increased316 // But only if from != to as we shouldn't check overflow in this case317 let account_balance_to = if create_target && from_to_differ {318 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))319 .checked_add(1)320 .ok_or(ArithmeticError::Overflow)?;321 ensure!(322 account_balance_to < collection.limits.account_token_ownership_limit(),323 <CommonError<T>>::AccountTokenLimitExceeded,324 );325326 Some(account_balance_to)327 } else {328 None329 };330331 // =========332333 if let Some(balance_to) = balance_to {334 // from != to335 if balance_from == 0 {336 <Balance<T>>::remove((collection.id, token, from));337 } else {338 <Balance<T>>::insert((collection.id, token, from), balance_from);339 }340 <Balance<T>>::insert((collection.id, token, to), balance_to);341 if let Some(account_balance_from) = account_balance_from {342 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);343 <Owned<T>>::remove((collection.id, from, token));344 }345 if let Some(account_balance_to) = account_balance_to {346 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);347 <Owned<T>>::insert((collection.id, to, token), true);348 }349 }350351 // TODO: ERC20 transfer event352 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(353 collection.id,354 token,355 from.clone(),356 to.clone(),357 amount,358 ));359 Ok(())360 }361362 pub fn create_multiple_items(363 collection: &RefungibleHandle<T>,364 sender: &T::CrossAccountId,365 data: Vec<CreateItemData<T>>,366 ) -> DispatchResult {367 if !collection.is_owner_or_admin(sender) {368 ensure!(369 collection.mint_mode,370 <CommonError<T>>::PublicMintingNotAllowed371 );372 collection.check_allowlist(sender)?;373374 for item in data.iter() {375 for user in item.users.keys() {376 collection.check_allowlist(user)?;377 }378 }379 }380381 for item in data.iter() {382 for (owner, _) in item.users.iter() {383 <PalletCommon<T>>::ensure_correct_receiver(owner)?;384 }385 }386387 // Total pieces per tokens388 let totals = data389 .iter()390 .map(|data| {391 Ok(data392 .users393 .iter()394 .map(|u| u.1)395 .try_fold(0u128, |acc, v| acc.checked_add(*v))396 .ok_or(ArithmeticError::Overflow)?)397 })398 .collect::<Result<Vec<_>, DispatchError>>()?;399 for total in &totals {400 ensure!(401 *total <= MAX_REFUNGIBLE_PIECES,402 <Error<T>>::WrongRefungiblePieces403 );404 }405406 let first_token_id = <TokensMinted<T>>::get(collection.id);407 let tokens_minted = first_token_id408 .checked_add(data.len() as u32)409 .ok_or(ArithmeticError::Overflow)?;410 ensure!(411 tokens_minted < collection.limits.token_limit(),412 <CommonError<T>>::CollectionTokenLimitExceeded413 );414415 let mut balances = BTreeMap::new();416 for data in &data {417 for owner in data.users.keys() {418 let balance = balances419 .entry(owner)420 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));421 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;422423 ensure!(424 *balance <= collection.limits.account_token_ownership_limit(),425 <CommonError<T>>::AccountTokenLimitExceeded,426 );427 }428 }429430 // =========431432 <TokensMinted<T>>::insert(collection.id, tokens_minted);433 for (account, balance) in balances {434 <AccountBalance<T>>::insert((collection.id, account), balance);435 }436 for (i, token) in data.into_iter().enumerate() {437 let token_id = first_token_id + i as u32 + 1;438 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);439440 <TokenData<T>>::insert(441 (collection.id, token_id),442 ItemData {443 const_data: token.const_data,444 variable_data: token.variable_data,445 },446 );447 for (user, amount) in token.users.into_iter() {448 if amount == 0 {449 continue;450 }451 <Balance<T>>::insert((collection.id, token_id, &user), amount);452 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);453 // TODO: ERC20 transfer event454 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(455 collection.id,456 TokenId(token_id),457 user,458 amount,459 ));460 }461 }462 Ok(())463 }464465 pub fn set_allowance_unchecked(466 collection: &RefungibleHandle<T>,467 sender: &T::CrossAccountId,468 spender: &T::CrossAccountId,469 token: TokenId,470 amount: u128,471 ) {472 if amount == 0 {473 <Allowance<T>>::remove((collection.id, token, sender, spender));474 } else {475 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);476 }477 // TODO: ERC20 approval event478 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(479 collection.id,480 token,481 sender.clone(),482 spender.clone(),483 amount,484 ))485 }486487 pub fn set_allowance(488 collection: &RefungibleHandle<T>,489 sender: &T::CrossAccountId,490 spender: &T::CrossAccountId,491 token: TokenId,492 amount: u128,493 ) -> DispatchResult {494 if collection.access == AccessMode::AllowList {495 collection.check_allowlist(sender)?;496 collection.check_allowlist(spender)?;497 }498499 <PalletCommon<T>>::ensure_correct_receiver(spender)?;500501 if <Balance<T>>::get((collection.id, token, sender)) < amount {502 ensure!(503 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),504 <CommonError<T>>::CantApproveMoreThanOwned505 );506 }507508 // =========509510 Self::set_allowance_unchecked(collection, sender, spender, token, amount);511 Ok(())512 }513514 pub fn transfer_from(515 collection: &RefungibleHandle<T>,516 spender: &T::CrossAccountId,517 from: &T::CrossAccountId,518 to: &T::CrossAccountId,519 token: TokenId,520 amount: u128,521 ) -> DispatchResult {522 if spender.conv_eq(from) {523 return Self::transfer(collection, from, to, token, amount);524 }525 if collection.access == AccessMode::AllowList {526 // `from`, `to` checked in [`transfer`]527 collection.check_allowlist(spender)?;528 }529530 let allowance =531 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);532 if allowance.is_none() {533 ensure!(534 collection.ignores_allowance(spender),535 <CommonError<T>>::TokenValueNotEnough536 );537 }538539 // =========540541 Self::transfer(collection, from, to, token, amount)?;542 if let Some(allowance) = allowance {543 Self::set_allowance_unchecked(collection, from, spender, token, allowance);544 }545 Ok(())546 }547548 pub fn burn_from(549 collection: &RefungibleHandle<T>,550 spender: &T::CrossAccountId,551 from: &T::CrossAccountId,552 token: TokenId,553 amount: u128,554 ) -> DispatchResult {555 if spender.conv_eq(from) {556 return Self::burn(collection, from, token, amount);557 }558 if collection.access == AccessMode::AllowList {559 // `from` checked in [`burn`]560 collection.check_allowlist(spender)?;561 }562563 let allowance =564 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);565 if allowance.is_none() {566 ensure!(567 collection.ignores_allowance(spender),568 <CommonError<T>>::TokenValueNotEnough569 );570 }571572 // =========573574 Self::burn(collection, from, token, amount)?;575 if let Some(allowance) = allowance {576 Self::set_allowance_unchecked(collection, from, spender, token, allowance);577 }578 Ok(())579 }580581 pub fn set_variable_metadata(582 collection: &RefungibleHandle<T>,583 sender: &T::CrossAccountId,584 token: TokenId,585 data: BoundedVec<u8, CustomDataLimit>,586 ) -> DispatchResult {587 collection.check_can_update_meta(588 sender,589 &T::CrossAccountId::from_sub(collection.owner.clone()),590 )?;591592 let token_data = <TokenData<T>>::get((collection.id, token));593594 // =========595596 <TokenData<T>>::insert(597 (collection.id, token),598 ItemData {599 variable_data: data,600 ..token_data601 },602 );603 Ok(())604 }605606 /// Delegated to `create_multiple_items`607 pub fn create_item(608 collection: &RefungibleHandle<T>,609 sender: &T::CrossAccountId,610 data: CreateItemData<T>,611 ) -> DispatchResult {612 Self::create_multiple_items(collection, sender, vec![data])613 }614}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());