difftreelog
feat allow more fields to be set on collection creation
in: master
7 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -14,7 +14,10 @@
COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,
MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_COLLECTION_NAME_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo, TokenId, Weight,
- WithdrawReasons, CollectionStats,
+ 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,
+ CreateCollectionData, SponsorshipState,
};
pub use pallet::*;
use sp_core::H160;
@@ -282,6 +285,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,
@@ -392,7 +399,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.name.len() <= MAX_COLLECTION_NAME_LENGTH,
@@ -423,6 +433,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 =
@@ -434,7 +467,7 @@
),
);
<T as Config>::Currency::settle(
- &data.owner,
+ &owner,
imbalance,
WithdrawReasons::TRANSFER,
ExistenceRequirement::KeepAlive,
@@ -443,12 +476,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)
}
@@ -532,6 +561,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
@@ -4,6 +4,7 @@
use frame_support::{BoundedVec, ensure};
use up_data_structs::{
AccessMode, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit, TokenId,
+ CreateCollectionData,
};
use pallet_common::{
Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,
@@ -142,8 +143,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, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit,6 MAX_REFUNGIBLE_PIECES, TokenId,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};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)]31pub struct ItemData {32 pub const_data: Vec<u8>,33 pub variable_data: Vec<u8>,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(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {160 <PalletCommon<T>>::init_collection(data)161 }162 pub fn destroy_collection(163 collection: RefungibleHandle<T>,164 sender: &T::CrossAccountId,165 ) -> DispatchResult {166 let id = collection.id;167168 // =========169170 PalletCommon::destroy_collection(collection.0, sender)?;171172 <TokensMinted<T>>::remove(id);173 <TokensBurnt<T>>::remove(id);174 <TokenData<T>>::remove_prefix((id,), None);175 <TotalSupply<T>>::remove_prefix((id,), None);176 <Balance<T>>::remove_prefix((id,), None);177 <Allowance<T>>::remove_prefix((id,), None);178 <Owned<T>>::remove_prefix((id,), None);179 <AccountBalance<T>>::remove_prefix((id,), None);180 Ok(())181 }182183 pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {184 let burnt = <TokensBurnt<T>>::get(collection.id)185 .checked_add(1)186 .ok_or(ArithmeticError::Overflow)?;187188 <TokensBurnt<T>>::insert(collection.id, burnt);189 <TokenData<T>>::remove((collection.id, token_id));190 <TotalSupply<T>>::remove((collection.id, token_id));191 <Balance<T>>::remove_prefix((collection.id, token_id), None);192 <Allowance<T>>::remove_prefix((collection.id, token_id), None);193 // TODO: ERC721 transfer event194 Ok(())195 }196197 pub fn burn(198 collection: &RefungibleHandle<T>,199 owner: &T::CrossAccountId,200 token: TokenId,201 amount: u128,202 ) -> DispatchResult {203 let total_supply = <TotalSupply<T>>::get((collection.id, token))204 .checked_sub(amount)205 .ok_or(<CommonError<T>>::TokenValueTooLow)?;206207 // This was probally last owner of this token?208 if total_supply == 0 {209 // Ensure user actually owns this amount210 ensure!(211 <Balance<T>>::get((collection.id, token, owner)) == amount,212 <CommonError<T>>::TokenValueTooLow213 );214 let account_balance = <AccountBalance<T>>::get((collection.id, owner))215 .checked_sub(1)216 // Should not occur217 .ok_or(ArithmeticError::Underflow)?;218219 // =========220221 <Owned<T>>::remove((collection.id, owner, token));222 <AccountBalance<T>>::insert((collection.id, owner), account_balance);223 Self::burn_token(collection, token)?;224 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(225 collection.id,226 token,227 owner.clone(),228 amount,229 ));230 return Ok(());231 }232233 let balance = <Balance<T>>::get((collection.id, token, owner))234 .checked_sub(amount)235 .ok_or(<CommonError<T>>::TokenValueTooLow)?;236 let account_balance = if balance == 0 {237 <AccountBalance<T>>::get((collection.id, owner))238 .checked_sub(1)239 // Should not occur240 .ok_or(ArithmeticError::Underflow)?241 } else {242 0243 };244245 // =========246247 if balance == 0 {248 <Owned<T>>::remove((collection.id, owner, token));249 <Balance<T>>::remove((collection.id, token, owner));250 <AccountBalance<T>>::insert((collection.id, owner), account_balance);251 } else {252 <Balance<T>>::insert((collection.id, token, owner), balance);253 }254 <TotalSupply<T>>::insert((collection.id, token), total_supply);255 // TODO: ERC20 transfer event256 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(257 collection.id,258 token,259 owner.clone(),260 amount,261 ));262 Ok(())263 }264265 pub fn transfer(266 collection: &RefungibleHandle<T>,267 from: &T::CrossAccountId,268 to: &T::CrossAccountId,269 token: TokenId,270 amount: u128,271 ) -> DispatchResult {272 ensure!(273 collection.limits.transfers_enabled(),274 <CommonError<T>>::TransferNotAllowed275 );276277 if collection.access == AccessMode::AllowList {278 collection.check_allowlist(from)?;279 collection.check_allowlist(to)?;280 }281 <PalletCommon<T>>::ensure_correct_receiver(to)?;282283 let balance_from = <Balance<T>>::get((collection.id, token, from))284 .checked_sub(amount)285 .ok_or(<CommonError<T>>::TokenValueTooLow)?;286 let mut create_target = false;287 let from_to_differ = from != to;288 let balance_to = if from != to {289 let old_balance = <Balance<T>>::get((collection.id, token, to));290 if old_balance == 0 {291 create_target = true;292 }293 Some(294 old_balance295 .checked_add(amount)296 .ok_or(ArithmeticError::Overflow)?,297 )298 } else {299 None300 };301302 let account_balance_from = if balance_from == 0 {303 Some(304 <AccountBalance<T>>::get((collection.id, from))305 .checked_sub(1)306 // Should not occur307 .ok_or(ArithmeticError::Underflow)?,308 )309 } else {310 None311 };312 // Account data is created in token, AccountBalance should be increased313 // But only if from != to as we shouldn't check overflow in this case314 let account_balance_to = if create_target && from_to_differ {315 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))316 .checked_add(1)317 .ok_or(ArithmeticError::Overflow)?;318 ensure!(319 account_balance_to < collection.limits.account_token_ownership_limit(),320 <CommonError<T>>::AccountTokenLimitExceeded,321 );322323 Some(account_balance_to)324 } else {325 None326 };327328 // =========329330 if let Some(balance_to) = balance_to {331 // from != to332 if balance_from == 0 {333 <Balance<T>>::remove((collection.id, token, from));334 } else {335 <Balance<T>>::insert((collection.id, token, from), balance_from);336 }337 <Balance<T>>::insert((collection.id, token, to), balance_to);338 if let Some(account_balance_from) = account_balance_from {339 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);340 <Owned<T>>::remove((collection.id, from, token));341 }342 if let Some(account_balance_to) = account_balance_to {343 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);344 <Owned<T>>::insert((collection.id, to, token), true);345 }346 }347348 // TODO: ERC20 transfer event349 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(350 collection.id,351 token,352 from.clone(),353 to.clone(),354 amount,355 ));356 Ok(())357 }358359 pub fn create_multiple_items(360 collection: &RefungibleHandle<T>,361 sender: &T::CrossAccountId,362 data: Vec<CreateItemData<T>>,363 ) -> DispatchResult {364 if !collection.is_owner_or_admin(sender) {365 ensure!(366 collection.mint_mode,367 <CommonError<T>>::PublicMintingNotAllowed368 );369 collection.check_allowlist(sender)?;370371 for item in data.iter() {372 for user in item.users.keys() {373 collection.check_allowlist(user)?;374 }375 }376 }377378 for item in data.iter() {379 for (owner, _) in item.users.iter() {380 <PalletCommon<T>>::ensure_correct_receiver(owner)?;381 }382 }383384 // Total pieces per tokens385 let totals = data386 .iter()387 .map(|data| {388 Ok(data389 .users390 .iter()391 .map(|u| u.1)392 .try_fold(0u128, |acc, v| acc.checked_add(*v))393 .ok_or(ArithmeticError::Overflow)?)394 })395 .collect::<Result<Vec<_>, DispatchError>>()?;396 for total in &totals {397 ensure!(398 *total <= MAX_REFUNGIBLE_PIECES,399 <Error<T>>::WrongRefungiblePieces400 );401 }402403 let first_token_id = <TokensMinted<T>>::get(collection.id);404 let tokens_minted = first_token_id405 .checked_add(data.len() as u32)406 .ok_or(ArithmeticError::Overflow)?;407 ensure!(408 tokens_minted < collection.limits.token_limit(),409 <CommonError<T>>::CollectionTokenLimitExceeded410 );411412 let mut balances = BTreeMap::new();413 for data in &data {414 for owner in data.users.keys() {415 let balance = balances416 .entry(owner)417 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));418 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;419420 ensure!(421 *balance <= collection.limits.account_token_ownership_limit(),422 <CommonError<T>>::AccountTokenLimitExceeded,423 );424 }425 }426427 // =========428429 <TokensMinted<T>>::insert(collection.id, tokens_minted);430 for (account, balance) in balances {431 <AccountBalance<T>>::insert((collection.id, account), balance);432 }433 for (i, token) in data.into_iter().enumerate() {434 let token_id = first_token_id + i as u32 + 1;435 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);436437 <TokenData<T>>::insert(438 (collection.id, token_id),439 ItemData {440 const_data: token.const_data.into(),441 variable_data: token.variable_data.into(),442 },443 );444 for (user, amount) in token.users.into_iter() {445 if amount == 0 {446 continue;447 }448 <Balance<T>>::insert((collection.id, token_id, &user), amount);449 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);450 // TODO: ERC20 transfer event451 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(452 collection.id,453 TokenId(token_id),454 user,455 amount,456 ));457 }458 }459 Ok(())460 }461462 pub fn set_allowance_unchecked(463 collection: &RefungibleHandle<T>,464 sender: &T::CrossAccountId,465 spender: &T::CrossAccountId,466 token: TokenId,467 amount: u128,468 ) {469 if amount == 0 {470 <Allowance<T>>::remove((collection.id, token, sender, spender));471 } else {472 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);473 }474 // TODO: ERC20 approval event475 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(476 collection.id,477 token,478 sender.clone(),479 spender.clone(),480 amount,481 ))482 }483484 pub fn set_allowance(485 collection: &RefungibleHandle<T>,486 sender: &T::CrossAccountId,487 spender: &T::CrossAccountId,488 token: TokenId,489 amount: u128,490 ) -> DispatchResult {491 if collection.access == AccessMode::AllowList {492 collection.check_allowlist(sender)?;493 collection.check_allowlist(spender)?;494 }495496 <PalletCommon<T>>::ensure_correct_receiver(spender)?;497498 if <Balance<T>>::get((collection.id, token, sender)) < amount {499 ensure!(500 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),501 <CommonError<T>>::CantApproveMoreThanOwned502 );503 }504505 // =========506507 Self::set_allowance_unchecked(collection, sender, spender, token, amount);508 Ok(())509 }510511 pub fn transfer_from(512 collection: &RefungibleHandle<T>,513 spender: &T::CrossAccountId,514 from: &T::CrossAccountId,515 to: &T::CrossAccountId,516 token: TokenId,517 amount: u128,518 ) -> DispatchResult {519 if spender.conv_eq(from) {520 return Self::transfer(collection, from, to, token, amount);521 }522 if collection.access == AccessMode::AllowList {523 // `from`, `to` checked in [`transfer`]524 collection.check_allowlist(spender)?;525 }526527 let allowance =528 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);529 if allowance.is_none() {530 ensure!(531 collection.ignores_allowance(spender),532 <CommonError<T>>::TokenValueNotEnough533 );534 }535536 // =========537538 Self::transfer(collection, from, to, token, amount)?;539 if let Some(allowance) = allowance {540 Self::set_allowance_unchecked(collection, from, spender, token, allowance);541 }542 Ok(())543 }544545 pub fn burn_from(546 collection: &RefungibleHandle<T>,547 spender: &T::CrossAccountId,548 from: &T::CrossAccountId,549 token: TokenId,550 amount: u128,551 ) -> DispatchResult {552 if spender.conv_eq(from) {553 return Self::burn(collection, from, token, amount);554 }555 if collection.access == AccessMode::AllowList {556 // `from` checked in [`burn`]557 collection.check_allowlist(spender)?;558 }559560 let allowance =561 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);562 if allowance.is_none() {563 ensure!(564 collection.ignores_allowance(spender),565 <CommonError<T>>::TokenValueNotEnough566 );567 }568569 // =========570571 Self::burn(collection, from, token, amount)?;572 if let Some(allowance) = allowance {573 Self::set_allowance_unchecked(collection, from, spender, token, allowance);574 }575 Ok(())576 }577578 pub fn set_variable_metadata(579 collection: &RefungibleHandle<T>,580 sender: &T::CrossAccountId,581 token: TokenId,582 data: Vec<u8>,583 ) -> DispatchResult {584 ensure!(585 data.len() as u32 <= CUSTOM_DATA_LIMIT,586 <CommonError<T>>::TokenVariableDataLimitExceeded587 );588 collection.check_can_update_meta(589 sender,590 &T::CrossAccountId::from_sub(collection.owner.clone()),591 )?;592593 let token_data = <TokenData<T>>::get((collection.id, token));594595 // =========596597 <TokenData<T>>::insert(598 (collection.id, token),599 ItemData {600 variable_data: data,601 ..token_data602 },603 );604 Ok(())605 }606607 /// Delegated to `create_multiple_items`608 pub fn create_item(609 collection: &RefungibleHandle<T>,610 sender: &T::CrossAccountId,611 data: CreateItemData<T>,612 ) -> DispatchResult {613 Self::create_multiple_items(collection, sender, vec![data])614 }615}pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -35,11 +35,10 @@
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, AccessMode, Collection, CreateItemData, CollectionLimits,
- CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
+ MAX_DECIMAL_POINTS, VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT,
+ OFFCHAIN_SCHEMA_LIMIT, AccessMode, CreateItemData, CollectionLimits, CollectionId,
+ CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
+ CreateCollectionData,
};
use pallet_common::{
account::CrossAccountId, CollectionHandle, Pallet as PalletCommon, Error as CommonError,
@@ -81,10 +80,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,
}
}
@@ -318,42 +313,38 @@
// returns collection ID
#[weight = <SelfWeightOf<T>>::create_collection()]
#[transactional]
+ #[deprecated]
pub fn create_collection(origin,
collection_name: Vec<u16>,
collection_description: Vec<u16>,
token_prefix: Vec<u8>,
mode: CollectionMode) -> DispatchResult {
-
- // Anyone can create a collection
- let who = ensure_signed(origin)?;
-
- // Create new collection
- let new_collection = Collection {
- owner: who,
+ Self::create_collection_ex(origin, CreateCollectionData {
name: collection_name,
- mode: mode.clone(),
- mint_mode: false,
- access: AccessMode::Normal,
description: collection_description,
token_prefix,
- offchain_schema: Vec::new(),
- schema_version: SchemaVersion::ImageURL,
- sponsorship: SponsorshipState::Disabled,
- variable_on_chain_schema: Vec::new(),
- const_on_chain_schema: Vec::new(),
- limits: Default::default(),
- meta_update_permission: Default::default(),
- };
+ mode,
+ ..Default::default()
+ })
+ }
+
+ /// 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)?
}
};
@@ -1099,61 +1090,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
@@ -230,6 +230,25 @@
pub meta_update_permission: MetaUpdatePermission,
}
+#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+#[derivative(Default)]
+pub struct CreateCollectionData<AccountId> {
+ #[derivative(Default(value = "CollectionMode::NFT"))]
+ pub mode: CollectionMode,
+ pub access: Option<AccessMode>,
+ pub name: Vec<u16>,
+ pub description: Vec<u16>,
+ pub token_prefix: Vec<u8>,
+ pub offchain_schema: Vec<u8>,
+ pub schema_version: Option<SchemaVersion>,
+ pub pending_sponsor: Option<AccountId>,
+ pub limits: Option<CollectionLimits>,
+ pub variable_on_chain_schema: Vec<u8>,
+ pub const_on_chain_schema: Vec<u8>,
+ pub meta_update_permission: Option<MetaUpdatePermission>,
+}
+
#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct NftItemType<AccountId> {