difftreelog
refactor make collection limits fields optional
in: master
8 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -105,10 +105,10 @@
Ok(())
}
pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> Result<bool, DispatchError> {
- Ok(self.limits.owner_can_transfer && self.is_owner_or_admin(user)?)
+ Ok(self.limits.owner_can_transfer() && self.is_owner_or_admin(user)?)
}
pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> Result<bool, DispatchError> {
- Ok(self.limits.owner_can_transfer && self.is_owner_or_admin(user)?)
+ Ok(self.limits.owner_can_transfer() && self.is_owner_or_admin(user)?)
}
pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {
self.consume_sload()?;
@@ -405,9 +405,10 @@
collection: CollectionHandle<T>,
sender: &T::CrossAccountId,
) -> DispatchResult {
- if !collection.limits.owner_can_destroy {
- fail!(Error::<T>::NoPermission);
- }
+ ensure!(
+ collection.limits.owner_can_destroy(),
+ <Error<T>>::NoPermission,
+ );
collection.check_is_owner(&sender)?;
let destroyed_collections = <DestroyedCollectionCount<T>>::get()
pallets/fungible/src/lib.rsdiffbeforeafterboth1#![cfg_attr(not(feature = "std"), no_std)]23use core::ops::Deref;4use frame_support::{ensure};5use nft_data_structs::{AccessMode, Collection, CollectionId, TokenId};6use pallet_common::{7 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,8};9use sp_core::H160;10use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};11use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};1213pub use pallet::*;1415use crate::erc::ERC20Events;16#[cfg(feature = "runtime-benchmarks")]17pub mod benchmarking;18pub mod common;19pub mod erc;20pub mod weights;2122pub type CreateItemData<T> = (<T as pallet_common::Config>::CrossAccountId, u128);23pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2425#[frame_support::pallet]26pub mod pallet {27 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};28 use nft_data_structs::CollectionId;29 use super::weights::WeightInfo;3031 #[pallet::error]32 pub enum Error<T> {33 /// Not Fungible item data used to mint in Fungible collection.34 NotFungibleDataUsedToMintFungibleCollectionToken,35 /// Not default id passed as TokenId argument36 FungibleItemsHaveNoId,37 /// Tried to set data for fungible item38 FungibleItemsHaveData,39 }4041 #[pallet::config]42 pub trait Config: frame_system::Config + pallet_common::Config {43 type WeightInfo: WeightInfo;44 }4546 #[pallet::pallet]47 #[pallet::generate_store(pub(super) trait Store)]48 pub struct Pallet<T>(_);4950 #[pallet::storage]51 pub(super) type TotalSupply<T: Config> =52 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;5354 #[pallet::storage]55 pub(super) type Balance<T: Config> = StorageNMap<56 Key = (57 Key<Twox64Concat, CollectionId>,58 Key<Blake2_128Concat, T::AccountId>,59 ),60 Value = u128,61 QueryKind = ValueQuery,62 >;6364 #[pallet::storage]65 pub(super) type Allowance<T: Config> = StorageNMap<66 Key = (67 Key<Twox64Concat, CollectionId>,68 Key<Blake2_128, T::AccountId>,69 Key<Blake2_128Concat, T::AccountId>,70 ),71 Value = u128,72 QueryKind = ValueQuery,73 >;74}7576pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);77impl<T: Config> FungibleHandle<T> {78 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {79 Self(inner)80 }81 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {82 self.083 }84}85impl<T: Config> Deref for FungibleHandle<T> {86 type Target = pallet_common::CollectionHandle<T>;8788 fn deref(&self) -> &Self::Target {89 &self.090 }91}9293impl<T: Config> Pallet<T> {94 pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {95 PalletCommon::init_collection(data)96 }97 pub fn destroy_collection(98 collection: FungibleHandle<T>,99 sender: &T::CrossAccountId,100 ) -> DispatchResult {101 let id = collection.id;102103 // =========104105 PalletCommon::destroy_collection(collection.0, sender)?;106107 <TotalSupply<T>>::remove(id);108 <Balance<T>>::remove_prefix((id,), None);109 <Allowance<T>>::remove_prefix((id,), None);110 Ok(())111 }112113 pub fn burn(114 collection: &FungibleHandle<T>,115 owner: &T::CrossAccountId,116 amount: u128,117 ) -> DispatchResult {118 let total_supply = <TotalSupply<T>>::get(collection.id)119 .checked_sub(amount)120 .ok_or(<CommonError<T>>::TokenValueTooLow)?;121122 let balance = <Balance<T>>::get((collection.id, owner.as_sub()))123 .checked_sub(amount)124 .ok_or(<CommonError<T>>::TokenValueTooLow)?;125126 if collection.access == AccessMode::WhiteList {127 collection.check_allowlist(owner)?;128 }129130 // =========131132 if balance == 0 {133 <Balance<T>>::remove((collection.id, owner.as_sub()));134 } else {135 <Balance<T>>::insert((collection.id, owner.as_sub()), balance);136 }137 <TotalSupply<T>>::insert(collection.id, total_supply);138139 collection.log_infallible(ERC20Events::Transfer {140 from: *owner.as_eth(),141 to: H160::default(),142 value: amount.into(),143 });144 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(145 collection.id,146 TokenId::default(),147 owner.clone(),148 amount,149 ));150 Ok(())151 }152153 pub fn transfer(154 collection: &FungibleHandle<T>,155 from: &T::CrossAccountId,156 to: &T::CrossAccountId,157 amount: u128,158 ) -> DispatchResult {159 ensure!(160 collection.transfers_enabled,161 <CommonError<T>>::TransferNotAllowed162 );163164 if collection.access == AccessMode::WhiteList {165 collection.check_allowlist(from)?;166 collection.check_allowlist(to)?;167 }168 <PalletCommon<T>>::ensure_correct_receiver(to)?;169170 let balance_from = <Balance<T>>::get((collection.id, from.as_sub()))171 .checked_sub(amount)172 .ok_or(<CommonError<T>>::TokenValueTooLow)?;173 let balance_to = if from != to {174 Some(175 <Balance<T>>::get((collection.id, to.as_sub()))176 .checked_add(amount)177 .ok_or(ArithmeticError::Overflow)?,178 )179 } else {180 None181 };182183 collection.consume_sstore()?;184 collection.consume_sstore()?;185 collection.consume_log(2, 32)?;186 collection.consume_sstore()?;187188 // =========189190 if let Some(balance_to) = balance_to {191 // from != to192 if balance_from == 0 {193 <Balance<T>>::remove((collection.id, from.as_sub()));194 } else {195 <Balance<T>>::insert((collection.id, from.as_sub()), balance_from);196 }197 <Balance<T>>::insert((collection.id, to.as_sub()), balance_to);198 }199200 collection.log_infallible(ERC20Events::Transfer {201 from: *from.as_eth(),202 to: *to.as_eth(),203 value: amount.into(),204 });205 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(206 collection.id,207 TokenId::default(),208 from.clone(),209 to.clone(),210 amount,211 ));212 Ok(())213 }214215 pub fn create_multiple_items(216 collection: &FungibleHandle<T>,217 sender: &T::CrossAccountId,218 data: Vec<CreateItemData<T>>,219 ) -> DispatchResult {220 let unrestricted_minting = collection.is_owner_or_admin(sender)?;221 if !unrestricted_minting {222 ensure!(223 collection.mint_mode,224 <CommonError<T>>::PublicMintingNotAllowed225 );226 collection.check_allowlist(sender)?;227228 for (owner, _) in data.iter() {229 collection.check_allowlist(owner)?;230 }231 }232233 let mut balances = BTreeMap::new();234235 let total_supply = data236 .iter()237 .map(|u| u.1)238 .try_fold(0u128, |acc, v| acc.checked_add(v))239 .ok_or(ArithmeticError::Overflow)?;240241 for (user, amount) in data.into_iter() {242 collection.consume_sload()?;243 let balance = balances244 .entry(user.clone())245 .or_insert_with(|| <Balance<T>>::get((collection.id, user.as_sub())));246 *balance = (*balance)247 .checked_add(amount)248 .ok_or(ArithmeticError::Overflow)?;249 }250251 collection.consume_sstore()?;252 for _ in &balances {253 collection.consume_sstore()?;254 collection.consume_log(2, 32)?;255 collection.consume_sstore()?;256 }257258 // =========259260 <TotalSupply<T>>::insert(collection.id, total_supply);261 for (user, amount) in balances {262 <Balance<T>>::insert((collection.id, user.as_sub()), amount);263264 collection.log_infallible(ERC20Events::Transfer {265 from: H160::default(),266 to: *user.as_eth(),267 value: amount.into(),268 });269 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(270 collection.id,271 TokenId::default(),272 user.clone(),273 amount,274 ));275 }276277 Ok(())278 }279280 fn set_allowance_unchecked(281 collection: &FungibleHandle<T>,282 owner: &T::CrossAccountId,283 spender: &T::CrossAccountId,284 amount: u128,285 ) {286 <Allowance<T>>::insert((collection.id, owner.as_sub(), spender.as_sub()), amount);287288 collection.log_infallible(ERC20Events::Approval {289 owner: *owner.as_eth(),290 spender: *spender.as_eth(),291 value: amount.into(),292 });293 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(294 collection.id,295 TokenId(0),296 owner.clone(),297 spender.clone(),298 amount,299 ));300 }301302 pub fn set_allowance(303 collection: &FungibleHandle<T>,304 owner: &T::CrossAccountId,305 spender: &T::CrossAccountId,306 amount: u128,307 ) -> DispatchResult {308 if collection.access == AccessMode::WhiteList {309 collection.check_allowlist(&owner)?;310 collection.check_allowlist(&spender)?;311 }312313 if <Balance<T>>::get((collection.id, owner.as_sub())) < amount {314 ensure!(315 collection.ignores_owned_amount(owner)?,316 <CommonError<T>>::CantApproveMoreThanOwned317 );318 }319320 // =========321322 Self::set_allowance_unchecked(collection, owner, spender, amount);323 Ok(())324 }325326 pub fn transfer_from(327 collection: &FungibleHandle<T>,328 spender: &T::CrossAccountId,329 from: &T::CrossAccountId,330 to: &T::CrossAccountId,331 amount: u128,332 ) -> DispatchResult {333 if spender == from {334 return Self::transfer(collection, from, to, amount);335 }336 if collection.access == AccessMode::WhiteList {337 // `from`, `to` checked in [`transfer`]338 collection.check_allowlist(spender)?;339 }340341 let allowance = <Allowance<T>>::get((collection.id, from.as_sub(), spender.as_sub()))342 .checked_sub(amount);343 if allowance.is_none() {344 ensure!(345 collection.ignores_allowance(spender)?,346 <CommonError<T>>::TokenValueNotEnough347 );348 }349350 // =========351352 Self::transfer(collection, from, to, amount)?;353 if let Some(allowance) = allowance {354 Self::set_allowance_unchecked(collection, from, spender, allowance);355 }356 Ok(())357 }358359 pub fn burn_from(360 collection: &FungibleHandle<T>,361 spender: &T::CrossAccountId,362 from: &T::CrossAccountId,363 amount: u128,364 ) -> DispatchResult {365 if spender == from {366 return Self::burn(collection, from, amount);367 }368 if collection.access == AccessMode::WhiteList {369 // `from` checked in [`burn`]370 collection.check_allowlist(spender)?;371 }372373 let allowance = <Allowance<T>>::get((collection.id, from.as_sub(), spender.as_sub()))374 .checked_sub(amount);375 if allowance.is_none() {376 ensure!(377 collection.ignores_allowance(spender)?,378 <CommonError<T>>::TokenValueNotEnough379 );380 }381382 // =========383384 Self::burn(collection, from, amount)?;385 if let Some(allowance) = allowance {386 Self::set_allowance_unchecked(collection, from, spender, allowance);387 }388 Ok(())389 }390391 /// Delegated to `create_multiple_items`392 pub fn create_item(393 collection: &FungibleHandle<T>,394 sender: &T::CrossAccountId,395 data: CreateItemData<T>,396 ) -> DispatchResult {397 Self::create_multiple_items(collection, sender, vec![data])398 }399}pallets/nft/src/eth/sponsoring.rsdiffbeforeafterboth--- a/pallets/nft/src/eth/sponsoring.rs
+++ b/pallets/nft/src/eth/sponsoring.rs
@@ -43,11 +43,8 @@
let token_id: u32 = token_id.try_into().map_err(|_| AnyError)?;
let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
let collection_limits = &collection.limits;
- let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
- collection_limits.sponsor_transfer_timeout
- } else {
- NFT_SPONSOR_TRANSFER_TIMEOUT
- };
+ let limit =
+ collection_limits.sponsor_transfer_timeout(NFT_SPONSOR_TRANSFER_TIMEOUT);
let mut sponsor = true;
if <NftTransferBasket<T>>::contains_key(collection_id, token_id) {
@@ -74,11 +71,8 @@
UniqueFungibleCall::ERC20(ERC20Call::Transfer { .. }) => {
let who = T::CrossAccountId::from_eth(*caller);
let collection_limits = &collection.limits;
- let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
- collection_limits.sponsor_transfer_timeout
- } else {
- FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT
- };
+ let limit = collection_limits
+ .sponsor_transfer_timeout(FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT);
let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
let mut sponsored = true;
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -37,8 +37,9 @@
use nft_data_structs::{
MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, CUSTOM_DATA_LIMIT,
VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, COLLECTION_ADMINS_LIMIT,
- OFFCHAIN_SCHEMA_LIMIT, AccessMode, Collection, CreateItemData, CollectionLimits, CollectionId,
- CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
+ 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,
};
use pallet_common::{
account::CrossAccountId, CollectionHandle, IsAdmin, Pallet as PalletCommon,
@@ -188,11 +189,6 @@
// Anyone can create a collection
let who = ensure_signed(origin)?;
-
- let limits = CollectionLimits::<T::BlockNumber> {
- sponsored_data_size: CUSTOM_DATA_LIMIT,
- ..Default::default()
- };
// Create new collection
let new_collection = Collection::<T> {
@@ -208,8 +204,7 @@
sponsorship: SponsorshipState::Disabled,
variable_on_chain_schema: Vec::new(),
const_on_chain_schema: Vec::new(),
- limits,
- transfers_enabled: true,
+ limits: Default::default(),
meta_update_permission: Default::default(),
};
@@ -582,7 +577,7 @@
// =========
- target_collection.transfers_enabled = value;
+ target_collection.limits.transfers_enabled = Some(value);
target_collection.save()
}
@@ -888,30 +883,63 @@
pub fn set_collection_limits(
origin,
collection_id: CollectionId,
- new_limits: CollectionLimits<T::BlockNumber>,
+ 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_limits = &target_collection.limits;
+ let old_limit = &target_collection.limits;
- // collection bounds
- ensure!(new_limits.sponsor_transfer_timeout <= MAX_SPONSOR_TIMEOUT &&
- new_limits.account_token_ownership_limit.unwrap_or(0) <= MAX_TOKEN_OWNERSHIP &&
- new_limits.sponsored_data_size <= CUSTOM_DATA_LIMIT,
- Error::<T>::CollectionLimitBoundsExceeded);
+ 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
+ }
+ )*
+ }};
+ }
- // token_limit check prev
- ensure!(old_limits.token_limit >= new_limits.token_limit, <CommonError<T>>::CollectionTokenLimitExceeded);
- ensure!(new_limits.token_limit > 0, <CommonError<T>>::CollectionTokenLimitExceeded);
-
- ensure!(
- (old_limits.owner_can_transfer || !new_limits.owner_can_transfer) &&
- (old_limits.owner_can_destroy || !new_limits.owner_can_destroy),
- Error::<T>::OwnerPermissionsCantBeReverted,
+ 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_limits;
+ target_collection.limits = new_limit;
target_collection.save()
}
pallets/nft/src/sponsorship.rsdiffbeforeafterboth--- a/pallets/nft/src/sponsorship.rs
+++ b/pallets/nft/src/sponsorship.rs
@@ -26,7 +26,13 @@
// sponsor timeout
let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
- let limit = collection.limits.sponsor_transfer_timeout;
+ let limit = collection
+ .limits
+ .sponsor_transfer_timeout(match _properties {
+ CreateItemData::NFT(_) => NFT_SPONSOR_TRANSFER_TIMEOUT,
+ CreateItemData::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+ CreateItemData::ReFungible(_) => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+ });
if CreateItemBasket::<T>::contains_key((collection_id, &who)) {
let last_tx_block = CreateItemBasket::<T>::get((collection_id, &who));
let limit_time = last_tx_block + limit.into();
@@ -37,7 +43,7 @@
CreateItemBasket::<T>::insert((collection_id, who.clone()), block_number);
// check free create limit
- if collection.limits.sponsored_data_size >= (_properties.data_size() as u32) {
+ if collection.limits.sponsored_data_size() >= (_properties.data_size() as u32) {
collection.sponsorship.sponsor().cloned()
} else {
None
@@ -61,11 +67,8 @@
sponsor_transfer = match collection_mode {
CollectionMode::NFT => {
// get correct limit
- let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
- collection_limits.sponsor_transfer_timeout
- } else {
- NFT_SPONSOR_TRANSFER_TIMEOUT
- };
+ let limit =
+ collection_limits.sponsor_transfer_timeout(NFT_SPONSOR_TRANSFER_TIMEOUT);
let mut sponsored = true;
if NftTransferBasket::<T>::contains_key(collection_id, item_id) {
@@ -83,11 +86,8 @@
}
CollectionMode::Fungible(_) => {
// get correct limit
- let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
- collection_limits.sponsor_transfer_timeout
- } else {
- FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT
- };
+ let limit = collection_limits
+ .sponsor_transfer_timeout(FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT);
let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
let mut sponsored = true;
@@ -106,11 +106,8 @@
}
CollectionMode::ReFungible => {
// get correct limit
- let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {
- collection_limits.sponsor_transfer_timeout
- } else {
- REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT
- };
+ let limit = collection_limits
+ .sponsor_transfer_timeout(REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT);
let mut sponsored = true;
if ReFungibleTransferBasket::<T>::contains_key(collection_id, item_id) {
@@ -150,13 +147,13 @@
// Can't sponsor fungible collection, this tx will be rejected
// as invalid
!matches!(collection.mode, CollectionMode::Fungible(_)) &&
- data.len() <= collection.limits.sponsored_data_size as usize
+ data.len() <= collection.limits.sponsored_data_size() as usize
{
- if let Some(rate_limit) = collection.limits.sponsored_data_rate_limit {
+ if let Some(rate_limit) = collection.limits.sponsored_data_rate_limit() {
let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
if VariableMetaDataBasket::<T>::get(collection_id, item_id)
- .map(|last_block| block_number - last_block > rate_limit)
+ .map(|last_block| block_number - last_block > rate_limit.into())
.unwrap_or(true)
{
sponsor_metadata_changes = true;
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -164,7 +164,7 @@
.ok_or_else(|| <CommonError<T>>::TokenNotFound)?;
ensure!(
&token_data.owner == sender
- || (collection.limits.owner_can_transfer
+ || (collection.limits.owner_can_transfer()
&& collection.is_owner_or_admin(sender)?),
<CommonError<T>>::NoPermission
);
@@ -215,7 +215,7 @@
token: TokenId,
) -> DispatchResult {
ensure!(
- collection.transfers_enabled,
+ collection.limits.transfers_enabled(),
<CommonError<T>>::TransferNotAllowed
);
@@ -223,7 +223,8 @@
.ok_or_else(|| <CommonError<T>>::TokenNotFound)?;
ensure!(
&token_data.owner == from
- || (collection.limits.owner_can_transfer && collection.is_owner_or_admin(from)?),
+ || (collection.limits.owner_can_transfer()
+ && collection.is_owner_or_admin(from)?),
<CommonError<T>>::NoPermission
);
@@ -327,7 +328,7 @@
.checked_add(data.len() as u32)
.ok_or(ArithmeticError::Overflow)?;
ensure!(
- tokens_minted < collection.limits.token_limit,
+ tokens_minted < collection.limits.token_limit(),
<CommonError<T>>::CollectionTokenLimitExceeded
);
collection.consume_sstore()?;
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -268,7 +268,7 @@
amount: u128,
) -> DispatchResult {
ensure!(
- collection.transfers_enabled,
+ collection.limits.transfers_enabled(),
<CommonError<T>>::TransferNotAllowed
);
@@ -404,7 +404,7 @@
.checked_add(data.len() as u32)
.ok_or(ArithmeticError::Overflow)?;
ensure!(
- tokens_minted < collection.limits.token_limit,
+ tokens_minted < collection.limits.token_limit(),
<CommonError<T>>::CollectionTokenLimitExceeded
);
primitives/nft/src/lib.rsdiffbeforeafterboth--- a/primitives/nft/src/lib.rs
+++ b/primitives/nft/src/lib.rs
@@ -42,6 +42,7 @@
10
};
pub const COLLECTION_ADMINS_LIMIT: u64 = 5;
+pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;
pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {
1000000
} else {
@@ -217,11 +218,10 @@
pub offchain_schema: Vec<u8>,
pub schema_version: SchemaVersion,
pub sponsorship: SponsorshipState<T::AccountId>,
- pub limits: CollectionLimits<T::BlockNumber>, // Collection private restrictions
- pub variable_on_chain_schema: Vec<u8>, //
- pub const_on_chain_schema: Vec<u8>, //
+ pub limits: CollectionLimits, // Collection private restrictions
+ pub variable_on_chain_schema: Vec<u8>, //
+ pub const_on_chain_schema: Vec<u8>, //
pub meta_update_permission: MetaUpdatePermission,
- pub transfers_enabled: bool,
}
#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]
@@ -246,42 +246,57 @@
pub variable_data: Vec<u8>,
}
-#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]
+#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-pub struct CollectionLimits<BlockNumber: Encode + Decode> {
+pub struct CollectionLimits {
pub account_token_ownership_limit: Option<u32>,
- pub sponsored_data_size: u32,
+ pub sponsored_data_size: Option<u32>,
/// None - setVariableMetadata is not sponsored
/// Some(v) - setVariableMetadata is sponsored
/// if there is v block between txs
- pub sponsored_data_rate_limit: Option<BlockNumber>,
- pub token_limit: u32,
+ pub sponsored_data_rate_limit: Option<u32>,
+ pub token_limit: Option<u32>,
// Timeouts for item types in passed blocks
- pub sponsor_transfer_timeout: u32,
- pub owner_can_transfer: bool,
- pub owner_can_destroy: bool,
+ pub sponsor_transfer_timeout: Option<u32>,
+ pub owner_can_transfer: Option<bool>,
+ pub owner_can_destroy: Option<bool>,
+ pub transfers_enabled: Option<bool>,
}
-impl<BlockNumber: Encode + Decode> CollectionLimits<BlockNumber> {
+impl CollectionLimits {
pub fn account_token_ownership_limit(&self) -> u32 {
self.account_token_ownership_limit
.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)
- .min(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)
+ .min(MAX_TOKEN_OWNERSHIP)
}
-}
-
-impl<BlockNumber: Encode + Decode> Default for CollectionLimits<BlockNumber> {
- fn default() -> Self {
- Self {
- account_token_ownership_limit: Some(10_000_000),
- token_limit: u32::max_value(),
- sponsored_data_size: u32::MAX,
- sponsored_data_rate_limit: None,
- sponsor_transfer_timeout: 14400,
- owner_can_transfer: true,
- owner_can_destroy: true,
- }
+ pub fn sponsored_data_size(&self) -> u32 {
+ self.sponsored_data_size
+ .unwrap_or(CUSTOM_DATA_LIMIT)
+ .min(CUSTOM_DATA_LIMIT)
+ }
+ pub fn token_limit(&self) -> u32 {
+ self.token_limit
+ .unwrap_or(COLLECTION_TOKEN_LIMIT)
+ .min(COLLECTION_TOKEN_LIMIT)
+ }
+ pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {
+ self.sponsor_transfer_timeout
+ .unwrap_or(default)
+ .min(MAX_SPONSOR_TIMEOUT)
+ }
+ pub fn owner_can_transfer(&self) -> bool {
+ self.owner_can_transfer.unwrap_or(true)
+ }
+ pub fn owner_can_destroy(&self) -> bool {
+ self.owner_can_destroy.unwrap_or(true)
+ }
+ pub fn transfers_enabled(&self) -> bool {
+ self.transfers_enabled.unwrap_or(true)
+ }
+ pub fn sponsored_data_rate_limit(&self) -> Option<u32> {
+ self.sponsored_data_rate_limit
+ .map(|v| v.min(MAX_SPONSOR_TIMEOUT))
}
}