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.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -157,8 +157,8 @@
amount: u128,
) -> DispatchResult {
ensure!(
- collection.transfers_enabled,
- <CommonError<T>>::TransferNotAllowed
+ collection.limits.transfers_enabled(),
+ <CommonError<T>>::TransferNotAllowed,
);
if collection.access == AccessMode::WhiteList {
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.rsdiffbeforeafterboth1#![cfg_attr(not(feature = "std"), no_std)]23use frame_support::{ensure, BoundedVec};4use nft_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 nft_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(super) type TokensMinted<T: Config> =62 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;63 #[pallet::storage]64 pub(super) type TokensBurnt<T: Config> =65 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6667 #[pallet::storage]68 pub(super) 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(super) 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(super) type Owned<T: Config> = StorageNMap<84 Key = (85 Key<Twox64Concat, CollectionId>,86 Key<Blake2_128Concat, T::AccountId>,87 Key<Twox64Concat, TokenId>,88 ),89 Value = bool,90 QueryKind = ValueQuery,91 >;9293 #[pallet::storage]94 pub(super) type AccountBalance<T: Config> = StorageNMap<95 Key = (96 Key<Twox64Concat, CollectionId>,97 // Owner98 Key<Blake2_128Concat, T::AccountId>,99 ),100 Value = u32,101 QueryKind = ValueQuery,102 >;103104 #[pallet::storage]105 pub(super) type Balance<T: Config> = StorageNMap<106 Key = (107 Key<Twox64Concat, CollectionId>,108 Key<Twox64Concat, TokenId>,109 // Owner110 Key<Blake2_128Concat, T::AccountId>,111 ),112 Value = u128,113 QueryKind = ValueQuery,114 >;115116 #[pallet::storage]117 pub(super) type Allowance<T: Config> = StorageNMap<118 Key = (119 Key<Twox64Concat, CollectionId>,120 Key<Twox64Concat, TokenId>,121 // Owner122 Key<Blake2_128, T::AccountId>,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>) -> Result<CollectionId, DispatchError> {160 PalletCommon::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 Ok(())179 }180181 pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {182 let burnt = <TokensBurnt<T>>::get(collection.id)183 .checked_add(1)184 .ok_or(ArithmeticError::Overflow)?;185186 <TokensBurnt<T>>::insert(collection.id, burnt);187 <TokenData<T>>::remove((collection.id, token_id));188 <TotalSupply<T>>::remove((collection.id, token_id));189 <Balance<T>>::remove_prefix((collection.id, token_id), None);190 <Allowance<T>>::remove_prefix((collection.id, token_id), None);191 // TODO: ERC721 transfer event192 return Ok(());193 }194195 pub fn burn(196 collection: &RefungibleHandle<T>,197 owner: &T::CrossAccountId,198 token: TokenId,199 amount: u128,200 ) -> DispatchResult {201 let total_supply = <TotalSupply<T>>::get((collection.id, token))202 .checked_sub(amount)203 .ok_or(<CommonError<T>>::TokenValueTooLow)?;204205 // This was probally last owner of this token?206 if total_supply == 0 {207 // Ensure user actually owns this amount208 ensure!(209 <Balance<T>>::get((collection.id, token, owner.as_sub())) == amount,210 <CommonError<T>>::TokenValueTooLow211 );212 let account_balance = <AccountBalance<T>>::get((collection.id, owner.as_sub()))213 .checked_sub(1)214 // Should not occur215 .ok_or(ArithmeticError::Underflow)?;216217 // =========218219 <Owned<T>>::remove((collection.id, owner.as_sub(), token));220 <AccountBalance<T>>::insert((collection.id, owner.as_sub()), account_balance);221 Self::burn_token(collection, token)?;222 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(223 collection.id,224 token,225 owner.clone(),226 amount,227 ));228 return Ok(());229 }230231 let balance = <Balance<T>>::get((collection.id, token, owner.as_sub()))232 .checked_sub(amount)233 .ok_or(<CommonError<T>>::TokenValueTooLow)?;234 let account_balance = if balance == 0 {235 <AccountBalance<T>>::get((collection.id, owner.as_sub()))236 .checked_sub(1)237 // Should not occur238 .ok_or(ArithmeticError::Underflow)?239 } else {240 0241 };242243 // =========244245 if balance == 0 {246 <Owned<T>>::remove((collection.id, owner.as_sub(), token));247 <Balance<T>>::remove((collection.id, token, owner.as_sub()));248 <AccountBalance<T>>::insert((collection.id, owner.as_sub()), account_balance);249 } else {250 <Balance<T>>::insert((collection.id, token, owner.as_sub()), balance);251 }252 <TotalSupply<T>>::insert((collection.id, token), total_supply);253 // TODO: ERC20 transfer event254 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(255 collection.id,256 token,257 owner.clone(),258 amount,259 ));260 Ok(())261 }262263 pub fn transfer(264 collection: &RefungibleHandle<T>,265 from: &T::CrossAccountId,266 to: &T::CrossAccountId,267 token: TokenId,268 amount: u128,269 ) -> DispatchResult {270 ensure!(271 collection.transfers_enabled,272 <CommonError<T>>::TransferNotAllowed273 );274275 if collection.access == AccessMode::WhiteList {276 collection.check_allowlist(from)?;277 collection.check_allowlist(to)?;278 }279 <PalletCommon<T>>::ensure_correct_receiver(to)?;280281 let balance_from = <Balance<T>>::get((collection.id, token, from.as_sub()))282 .checked_sub(amount)283 .ok_or(<CommonError<T>>::TokenValueTooLow)?;284 let mut create_target = false;285 let from_to_differ = from != to;286 let balance_to = if from != to {287 let old_balance = <Balance<T>>::get((collection.id, token, to.as_sub()));288 if old_balance == 0 {289 create_target = true;290 }291 Some(292 old_balance293 .checked_add(amount)294 .ok_or(ArithmeticError::Overflow)?,295 )296 } else {297 None298 };299300 let account_balance_from = if balance_from == 0 {301 Some(302 <AccountBalance<T>>::get((collection.id, from.as_sub()))303 .checked_sub(1)304 // Should not occur305 .ok_or(ArithmeticError::Underflow)?,306 )307 } else {308 None309 };310 // Account data is created in token, AccountBalance should be increased311 // But only if from != to as we shouldn't check overflow in this case312 let account_balance_to = if create_target && from_to_differ {313 let account_balance_to = <AccountBalance<T>>::get((collection.id, to.as_sub()))314 .checked_add(1)315 .ok_or(ArithmeticError::Overflow)?;316 ensure!(317 account_balance_to < collection.limits.account_token_ownership_limit(),318 <CommonError<T>>::AccountTokenLimitExceeded,319 );320321 Some(account_balance_to)322 } else {323 None324 };325326 // =========327328 if let Some(balance_to) = balance_to {329 // from != to330 if balance_from == 0 {331 <Balance<T>>::remove((collection.id, token, from.as_sub()));332 } else {333 <Balance<T>>::insert((collection.id, token, from.as_sub()), balance_from);334 }335 <Balance<T>>::insert((collection.id, token, to.as_sub()), balance_to);336 if let Some(account_balance_from) = account_balance_from {337 <AccountBalance<T>>::insert((collection.id, from.as_sub()), account_balance_from);338 <Owned<T>>::remove((collection.id, from.as_sub(), token));339 }340 if let Some(account_balance_to) = account_balance_to {341 <AccountBalance<T>>::insert((collection.id, to.as_sub()), account_balance_to);342 <Owned<T>>::insert((collection.id, to.as_sub(), token), true);343 }344 }345346 // TODO: ERC20 transfer event347 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(348 collection.id,349 token,350 from.clone(),351 to.clone(),352 amount,353 ));354 Ok(())355 }356357 pub fn create_multiple_items(358 collection: &RefungibleHandle<T>,359 sender: &T::CrossAccountId,360 data: Vec<CreateItemData<T>>,361 ) -> DispatchResult {362 let unrestricted_minting = collection.is_owner_or_admin(sender)?;363 if !unrestricted_minting {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 {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 {414 let balance = balances415 .entry(owner.as_sub())416 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner.as_sub())));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.into(),440 variable_data: token.variable_data.into(),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.as_sub()), amount);448 <Owned<T>>::insert((collection.id, user.as_sub(), 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 <Allowance<T>>::insert((collection.id, token, sender.as_sub(), spender), amount);469 // TODO: ERC20 approval event470 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(471 collection.id,472 token,473 sender.clone(),474 spender.clone(),475 amount,476 ))477 }478479 pub fn set_allowance(480 collection: &RefungibleHandle<T>,481 sender: &T::CrossAccountId,482 spender: &T::CrossAccountId,483 token: TokenId,484 amount: u128,485 ) -> DispatchResult {486 if collection.access == AccessMode::WhiteList {487 collection.check_allowlist(&sender)?;488 collection.check_allowlist(&spender)?;489 }490491 <PalletCommon<T>>::ensure_correct_receiver(spender)?;492493 if <Balance<T>>::get((collection.id, token, sender.as_sub())) < amount {494 ensure!(495 collection.ignores_owned_amount(sender)? && Self::token_exists(collection, token),496 <CommonError<T>>::CantApproveMoreThanOwned497 );498 }499500 // =========501502 Self::set_allowance_unchecked(collection, sender, spender, token, amount);503 Ok(())504 }505506 pub fn transfer_from(507 collection: &RefungibleHandle<T>,508 spender: &T::CrossAccountId,509 from: &T::CrossAccountId,510 to: &T::CrossAccountId,511 token: TokenId,512 amount: u128,513 ) -> DispatchResult {514 if spender == from {515 return Self::transfer(collection, from, to, token, amount);516 }517 if collection.access == AccessMode::WhiteList {518 // `from`, `to` checked in [`transfer`]519 collection.check_allowlist(spender)?;520 }521522 let allowance = <Allowance<T>>::get((collection.id, token, from.as_sub(), &spender))523 .checked_sub(amount);524 if allowance.is_none() {525 ensure!(526 collection.ignores_allowance(spender)?,527 <CommonError<T>>::TokenValueNotEnough528 );529 }530531 // =========532533 Self::transfer(collection, from, to, token, amount)?;534 if let Some(allowance) = allowance {535 Self::set_allowance_unchecked(collection, from, spender, token, allowance);536 }537 Ok(())538 }539540 pub fn burn_from(541 collection: &RefungibleHandle<T>,542 spender: &T::CrossAccountId,543 from: &T::CrossAccountId,544 token: TokenId,545 amount: u128,546 ) -> DispatchResult {547 if spender == from {548 return Self::burn(collection, from, token, amount);549 }550 if collection.access == AccessMode::WhiteList {551 // `from` checked in [`burn`]552 collection.check_allowlist(spender)?;553 }554555 let allowance = <Allowance<T>>::get((collection.id, token, from.as_sub(), &spender))556 .checked_sub(amount);557 if allowance.is_none() {558 ensure!(559 collection.ignores_allowance(spender)?,560 <CommonError<T>>::TokenValueNotEnough561 );562 }563564 // =========565566 Self::burn(collection, from, token, amount)?;567 if let Some(allowance) = allowance {568 Self::set_allowance_unchecked(collection, from, spender, token, allowance);569 }570 Ok(())571 }572573 pub fn set_variable_metadata(574 collection: &RefungibleHandle<T>,575 sender: &T::CrossAccountId,576 token: TokenId,577 data: Vec<u8>,578 ) -> DispatchResult {579 ensure!(580 data.len() as u32 <= CUSTOM_DATA_LIMIT,581 <CommonError<T>>::TokenVariableDataLimitExceeded582 );583 collection.check_can_update_meta(584 sender,585 &T::CrossAccountId::from_sub(collection.owner.clone()),586 )?;587588 collection.consume_sstore()?;589 let token_data = <TokenData<T>>::get((collection.id, token));590591 // =========592593 <TokenData<T>>::insert(594 (collection.id, token),595 ItemData {596 variable_data: data,597 ..token_data598 },599 );600 Ok(())601 }602603 /// Delegated to `create_multiple_items`604 pub fn create_item(605 collection: &RefungibleHandle<T>,606 sender: &T::CrossAccountId,607 data: CreateItemData<T>,608 ) -> DispatchResult {609 Self::create_multiple_items(collection, sender, vec![data])610 }611}1#![cfg_attr(not(feature = "std"), no_std)]23use frame_support::{ensure, BoundedVec};4use nft_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 nft_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(super) type TokensMinted<T: Config> =62 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;63 #[pallet::storage]64 pub(super) type TokensBurnt<T: Config> =65 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6667 #[pallet::storage]68 pub(super) 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(super) 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(super) type Owned<T: Config> = StorageNMap<84 Key = (85 Key<Twox64Concat, CollectionId>,86 Key<Blake2_128Concat, T::AccountId>,87 Key<Twox64Concat, TokenId>,88 ),89 Value = bool,90 QueryKind = ValueQuery,91 >;9293 #[pallet::storage]94 pub(super) type AccountBalance<T: Config> = StorageNMap<95 Key = (96 Key<Twox64Concat, CollectionId>,97 // Owner98 Key<Blake2_128Concat, T::AccountId>,99 ),100 Value = u32,101 QueryKind = ValueQuery,102 >;103104 #[pallet::storage]105 pub(super) type Balance<T: Config> = StorageNMap<106 Key = (107 Key<Twox64Concat, CollectionId>,108 Key<Twox64Concat, TokenId>,109 // Owner110 Key<Blake2_128Concat, T::AccountId>,111 ),112 Value = u128,113 QueryKind = ValueQuery,114 >;115116 #[pallet::storage]117 pub(super) type Allowance<T: Config> = StorageNMap<118 Key = (119 Key<Twox64Concat, CollectionId>,120 Key<Twox64Concat, TokenId>,121 // Owner122 Key<Blake2_128, T::AccountId>,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>) -> Result<CollectionId, DispatchError> {160 PalletCommon::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 Ok(())179 }180181 pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {182 let burnt = <TokensBurnt<T>>::get(collection.id)183 .checked_add(1)184 .ok_or(ArithmeticError::Overflow)?;185186 <TokensBurnt<T>>::insert(collection.id, burnt);187 <TokenData<T>>::remove((collection.id, token_id));188 <TotalSupply<T>>::remove((collection.id, token_id));189 <Balance<T>>::remove_prefix((collection.id, token_id), None);190 <Allowance<T>>::remove_prefix((collection.id, token_id), None);191 // TODO: ERC721 transfer event192 return Ok(());193 }194195 pub fn burn(196 collection: &RefungibleHandle<T>,197 owner: &T::CrossAccountId,198 token: TokenId,199 amount: u128,200 ) -> DispatchResult {201 let total_supply = <TotalSupply<T>>::get((collection.id, token))202 .checked_sub(amount)203 .ok_or(<CommonError<T>>::TokenValueTooLow)?;204205 // This was probally last owner of this token?206 if total_supply == 0 {207 // Ensure user actually owns this amount208 ensure!(209 <Balance<T>>::get((collection.id, token, owner.as_sub())) == amount,210 <CommonError<T>>::TokenValueTooLow211 );212 let account_balance = <AccountBalance<T>>::get((collection.id, owner.as_sub()))213 .checked_sub(1)214 // Should not occur215 .ok_or(ArithmeticError::Underflow)?;216217 // =========218219 <Owned<T>>::remove((collection.id, owner.as_sub(), token));220 <AccountBalance<T>>::insert((collection.id, owner.as_sub()), account_balance);221 Self::burn_token(collection, token)?;222 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(223 collection.id,224 token,225 owner.clone(),226 amount,227 ));228 return Ok(());229 }230231 let balance = <Balance<T>>::get((collection.id, token, owner.as_sub()))232 .checked_sub(amount)233 .ok_or(<CommonError<T>>::TokenValueTooLow)?;234 let account_balance = if balance == 0 {235 <AccountBalance<T>>::get((collection.id, owner.as_sub()))236 .checked_sub(1)237 // Should not occur238 .ok_or(ArithmeticError::Underflow)?239 } else {240 0241 };242243 // =========244245 if balance == 0 {246 <Owned<T>>::remove((collection.id, owner.as_sub(), token));247 <Balance<T>>::remove((collection.id, token, owner.as_sub()));248 <AccountBalance<T>>::insert((collection.id, owner.as_sub()), account_balance);249 } else {250 <Balance<T>>::insert((collection.id, token, owner.as_sub()), balance);251 }252 <TotalSupply<T>>::insert((collection.id, token), total_supply);253 // TODO: ERC20 transfer event254 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(255 collection.id,256 token,257 owner.clone(),258 amount,259 ));260 Ok(())261 }262263 pub fn transfer(264 collection: &RefungibleHandle<T>,265 from: &T::CrossAccountId,266 to: &T::CrossAccountId,267 token: TokenId,268 amount: u128,269 ) -> DispatchResult {270 ensure!(271 collection.limits.transfers_enabled(),272 <CommonError<T>>::TransferNotAllowed273 );274275 if collection.access == AccessMode::WhiteList {276 collection.check_allowlist(from)?;277 collection.check_allowlist(to)?;278 }279 <PalletCommon<T>>::ensure_correct_receiver(to)?;280281 let balance_from = <Balance<T>>::get((collection.id, token, from.as_sub()))282 .checked_sub(amount)283 .ok_or(<CommonError<T>>::TokenValueTooLow)?;284 let mut create_target = false;285 let from_to_differ = from != to;286 let balance_to = if from != to {287 let old_balance = <Balance<T>>::get((collection.id, token, to.as_sub()));288 if old_balance == 0 {289 create_target = true;290 }291 Some(292 old_balance293 .checked_add(amount)294 .ok_or(ArithmeticError::Overflow)?,295 )296 } else {297 None298 };299300 let account_balance_from = if balance_from == 0 {301 Some(302 <AccountBalance<T>>::get((collection.id, from.as_sub()))303 .checked_sub(1)304 // Should not occur305 .ok_or(ArithmeticError::Underflow)?,306 )307 } else {308 None309 };310 // Account data is created in token, AccountBalance should be increased311 // But only if from != to as we shouldn't check overflow in this case312 let account_balance_to = if create_target && from_to_differ {313 let account_balance_to = <AccountBalance<T>>::get((collection.id, to.as_sub()))314 .checked_add(1)315 .ok_or(ArithmeticError::Overflow)?;316 ensure!(317 account_balance_to < collection.limits.account_token_ownership_limit(),318 <CommonError<T>>::AccountTokenLimitExceeded,319 );320321 Some(account_balance_to)322 } else {323 None324 };325326 // =========327328 if let Some(balance_to) = balance_to {329 // from != to330 if balance_from == 0 {331 <Balance<T>>::remove((collection.id, token, from.as_sub()));332 } else {333 <Balance<T>>::insert((collection.id, token, from.as_sub()), balance_from);334 }335 <Balance<T>>::insert((collection.id, token, to.as_sub()), balance_to);336 if let Some(account_balance_from) = account_balance_from {337 <AccountBalance<T>>::insert((collection.id, from.as_sub()), account_balance_from);338 <Owned<T>>::remove((collection.id, from.as_sub(), token));339 }340 if let Some(account_balance_to) = account_balance_to {341 <AccountBalance<T>>::insert((collection.id, to.as_sub()), account_balance_to);342 <Owned<T>>::insert((collection.id, to.as_sub(), token), true);343 }344 }345346 // TODO: ERC20 transfer event347 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(348 collection.id,349 token,350 from.clone(),351 to.clone(),352 amount,353 ));354 Ok(())355 }356357 pub fn create_multiple_items(358 collection: &RefungibleHandle<T>,359 sender: &T::CrossAccountId,360 data: Vec<CreateItemData<T>>,361 ) -> DispatchResult {362 let unrestricted_minting = collection.is_owner_or_admin(sender)?;363 if !unrestricted_minting {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 {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 {414 let balance = balances415 .entry(owner.as_sub())416 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner.as_sub())));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.into(),440 variable_data: token.variable_data.into(),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.as_sub()), amount);448 <Owned<T>>::insert((collection.id, user.as_sub(), 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 <Allowance<T>>::insert((collection.id, token, sender.as_sub(), spender), amount);469 // TODO: ERC20 approval event470 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(471 collection.id,472 token,473 sender.clone(),474 spender.clone(),475 amount,476 ))477 }478479 pub fn set_allowance(480 collection: &RefungibleHandle<T>,481 sender: &T::CrossAccountId,482 spender: &T::CrossAccountId,483 token: TokenId,484 amount: u128,485 ) -> DispatchResult {486 if collection.access == AccessMode::WhiteList {487 collection.check_allowlist(&sender)?;488 collection.check_allowlist(&spender)?;489 }490491 <PalletCommon<T>>::ensure_correct_receiver(spender)?;492493 if <Balance<T>>::get((collection.id, token, sender.as_sub())) < amount {494 ensure!(495 collection.ignores_owned_amount(sender)? && Self::token_exists(collection, token),496 <CommonError<T>>::CantApproveMoreThanOwned497 );498 }499500 // =========501502 Self::set_allowance_unchecked(collection, sender, spender, token, amount);503 Ok(())504 }505506 pub fn transfer_from(507 collection: &RefungibleHandle<T>,508 spender: &T::CrossAccountId,509 from: &T::CrossAccountId,510 to: &T::CrossAccountId,511 token: TokenId,512 amount: u128,513 ) -> DispatchResult {514 if spender == from {515 return Self::transfer(collection, from, to, token, amount);516 }517 if collection.access == AccessMode::WhiteList {518 // `from`, `to` checked in [`transfer`]519 collection.check_allowlist(spender)?;520 }521522 let allowance = <Allowance<T>>::get((collection.id, token, from.as_sub(), &spender))523 .checked_sub(amount);524 if allowance.is_none() {525 ensure!(526 collection.ignores_allowance(spender)?,527 <CommonError<T>>::TokenValueNotEnough528 );529 }530531 // =========532533 Self::transfer(collection, from, to, token, amount)?;534 if let Some(allowance) = allowance {535 Self::set_allowance_unchecked(collection, from, spender, token, allowance);536 }537 Ok(())538 }539540 pub fn burn_from(541 collection: &RefungibleHandle<T>,542 spender: &T::CrossAccountId,543 from: &T::CrossAccountId,544 token: TokenId,545 amount: u128,546 ) -> DispatchResult {547 if spender == from {548 return Self::burn(collection, from, token, amount);549 }550 if collection.access == AccessMode::WhiteList {551 // `from` checked in [`burn`]552 collection.check_allowlist(spender)?;553 }554555 let allowance = <Allowance<T>>::get((collection.id, token, from.as_sub(), &spender))556 .checked_sub(amount);557 if allowance.is_none() {558 ensure!(559 collection.ignores_allowance(spender)?,560 <CommonError<T>>::TokenValueNotEnough561 );562 }563564 // =========565566 Self::burn(collection, from, token, amount)?;567 if let Some(allowance) = allowance {568 Self::set_allowance_unchecked(collection, from, spender, token, allowance);569 }570 Ok(())571 }572573 pub fn set_variable_metadata(574 collection: &RefungibleHandle<T>,575 sender: &T::CrossAccountId,576 token: TokenId,577 data: Vec<u8>,578 ) -> DispatchResult {579 ensure!(580 data.len() as u32 <= CUSTOM_DATA_LIMIT,581 <CommonError<T>>::TokenVariableDataLimitExceeded582 );583 collection.check_can_update_meta(584 sender,585 &T::CrossAccountId::from_sub(collection.owner.clone()),586 )?;587588 collection.consume_sstore()?;589 let token_data = <TokenData<T>>::get((collection.id, token));590591 // =========592593 <TokenData<T>>::insert(594 (collection.id, token),595 ItemData {596 variable_data: data,597 ..token_data598 },599 );600 Ok(())601 }602603 /// Delegated to `create_multiple_items`604 pub fn create_item(605 collection: &RefungibleHandle<T>,606 sender: &T::CrossAccountId,607 data: CreateItemData<T>,608 ) -> DispatchResult {609 Self::create_multiple_items(collection, sender, vec![data])610 }611}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))
}
}