difftreelog
Add properties key chars check
in: master
4 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -18,7 +18,7 @@
use core::ops::{Deref, DerefMut};
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
-use sp_std::{vec::Vec, collections::btree_map::BTreeMap};
+use sp_std::vec::Vec;
use pallet_evm::account::CrossAccountId;
use frame_support::{
dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},
@@ -36,7 +36,7 @@
CUSTOM_DATA_LIMIT, CollectionLimits, CustomDataLimit, CreateCollectionData, SponsorshipState,
CreateItemExData, SponsoringRateLimit, budget::Budget, COLLECTION_FIELD_LIMIT, CollectionField,
PhantomType, Property, Properties, PropertiesPermissionMap, PropertyKey, PropertyPermission,
- PropertiesError, PropertyKeyPermission, TokenData, CollectionPropertiesPermissionsVec,
+ PropertiesError, PropertyKeyPermission, TokenData, TrySet,
};
pub use pallet::*;
use sp_core::H160;
@@ -374,6 +374,9 @@
/// Unable to read array of unbounded keys
UnableToReadUnboundedKeys,
+
+ /// Only ASCII letters, digits, and '_', '-' are allowed
+ InvalidCharacterInPropertyKey,
}
#[pallet::storage]
@@ -676,19 +679,20 @@
meta_update_permission: data.meta_update_permission.unwrap_or_default(),
};
- CollectionProperties::<T>::insert(
- id,
- Properties::from_collection_props_vec(data.properties)
- .map_err(|e| -> Error<T> { e.into() })?,
- );
+ let mut collection_properties = up_data_structs::CollectionProperties::get();
+ collection_properties.try_set_from_iter(
+ data.properties.into_iter()
+ .map(|p| (p.key, p.value))
+ ).map_err(|e| -> Error<T> { e.into() })?;
+
+ CollectionProperties::<T>::insert(id, collection_properties);
- let token_props_permissions: PropertiesPermissionMap = data
- .token_property_permissions
+ let mut token_props_permissions = PropertiesPermissionMap::new();
+ token_props_permissions.try_set_from_iter(
+ data.token_property_permissions
.into_iter()
.map(|property| (property.key, property.permission))
- .collect::<BTreeMap<_, _>>()
- .try_into()
- .map_err(|_| -> Error<T> { PropertiesError::PropertyLimitReached.into() })?;
+ ).map_err(|e| -> Error<T> { e.into() })?;
CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);
@@ -771,7 +775,8 @@
collection.check_is_owner_or_admin(sender)?;
CollectionProperties::<T>::try_mutate(collection.id, |properties| {
- properties.try_set_property(property.clone())
+ let property = property.clone();
+ properties.try_set(property.key, property.value)
})
.map_err(|e| -> Error<T> { e.into() })?;
@@ -799,9 +804,9 @@
) -> DispatchResult {
collection.check_is_owner_or_admin(sender)?;
- CollectionProperties::<T>::mutate(collection.id, |properties| {
- properties.remove_property(&property_key);
- });
+ CollectionProperties::<T>::try_mutate(collection.id, |properties| {
+ properties.remove(&property_key)
+ }).map_err(|e| -> Error<T> { e.into() })?;
Self::deposit_event(Event::CollectionPropertyDeleted(
collection.id,
@@ -841,7 +846,7 @@
CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {
let property_permission = property_permission.clone();
- permissions.try_insert(property_permission.key, property_permission.permission)
+ permissions.try_set(property_permission.key, property_permission.permission)
})
.map_err(|_| -> Error<T> { PropertiesError::PropertyLimitReached.into() })?;
@@ -876,6 +881,19 @@
.collect::<Result<Vec<PropertyKey>, DispatchError>>()
}
+ pub fn check_property_key(key: &PropertyKey) -> Result<(), DispatchError> {
+ let key_str = sp_std::str::from_utf8(key.as_slice())
+ .map_err(|_| <Error<T>>::InvalidCharacterInPropertyKey)?;
+
+ for ch in key_str.chars() {
+ if !ch.is_ascii_alphanumeric() && ch != '_' && ch != '-' {
+ return Err(<Error<T>>::InvalidCharacterInPropertyKey.into());
+ }
+ }
+
+ Ok(())
+ }
+
pub fn filter_collection_properties(
collection_id: CollectionId,
keys: Vec<PropertyKey>,
@@ -885,10 +903,11 @@
let properties = keys
.into_iter()
.filter_map(|key| {
- properties.get_property(&key).map(|value| Property {
- key,
- value: value.clone(),
- })
+ properties.get(&key)
+ .map(|value| Property {
+ key,
+ value: value.clone(),
+ })
})
.collect();
@@ -1222,6 +1241,7 @@
match error {
PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,
PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,
+ PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,
}
}
}
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -391,10 +391,11 @@
keys.into_iter()
.filter_map(|key| {
- properties.get_property(&key).map(|value| Property {
- key,
- value: value.clone(),
- })
+ properties.get(&key)
+ .map(|value| Property {
+ key,
+ value: value.clone(),
+ })
})
.collect()
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use erc::ERC721Events;20use frame_support::{BoundedVec, ensure, fail};21use up_data_structs::{22 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,23 mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,24 PropertyKey, PropertyKeyPermission, Properties,25};26use pallet_evm::account::CrossAccountId;27use pallet_common::{28 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,29 dispatch::CollectionDispatch,30};31use pallet_structure::Pallet as PalletStructure;32use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};33use sp_core::H160;34use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};35use sp_std::{vec::Vec, vec};36use core::ops::Deref;37use sp_std::collections::btree_map::BTreeMap;38use codec::{Encode, Decode, MaxEncodedLen};39use scale_info::TypeInfo;4041pub use pallet::*;42#[cfg(feature = "runtime-benchmarks")]43pub mod benchmarking;44pub mod common;45pub mod erc;46pub mod weights;4748pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;49pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;5051#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]52pub struct ItemData<CrossAccountId> {53 pub const_data: BoundedVec<u8, CustomDataLimit>,54 pub variable_data: BoundedVec<u8, CustomDataLimit>,55 pub owner: CrossAccountId,56}5758#[frame_support::pallet]59pub mod pallet {60 use super::*;61 use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};62 use up_data_structs::{CollectionId, TokenId};63 use super::weights::WeightInfo;6465 #[pallet::error]66 pub enum Error<T> {67 /// Not Nonfungible item data used to mint in Nonfungible collection.68 NotNonfungibleDataUsedToMintFungibleCollectionToken,69 /// Used amount > 1 with NFT70 NonfungibleItemsHaveNoAmount,71 }7273 #[pallet::config]74 pub trait Config:75 frame_system::Config + pallet_common::Config + pallet_structure::Config76 {77 type WeightInfo: WeightInfo;78 }7980 #[pallet::pallet]81 #[pallet::generate_store(pub(super) trait Store)]82 pub struct Pallet<T>(_);8384 #[pallet::storage]85 pub type TokensMinted<T: Config> =86 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;87 #[pallet::storage]88 pub type TokensBurnt<T: Config> =89 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;9091 #[pallet::storage]92 pub type TokenData<T: Config> = StorageNMap<93 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),94 Value = ItemData<T::CrossAccountId>,95 QueryKind = OptionQuery,96 >;9798 #[pallet::storage]99 #[pallet::getter(fn token_properties)]100 pub type TokenProperties<T: Config> = StorageNMap<101 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),102 Value = Properties,103 QueryKind = ValueQuery,104 OnEmpty = up_data_structs::TokenProperties,105 >;106107 /// Used to enumerate tokens owned by account108 #[pallet::storage]109 pub type Owned<T: Config> = StorageNMap<110 Key = (111 Key<Twox64Concat, CollectionId>,112 Key<Blake2_128Concat, T::CrossAccountId>,113 Key<Twox64Concat, TokenId>,114 ),115 Value = bool,116 QueryKind = ValueQuery,117 >;118119 #[pallet::storage]120 pub type AccountBalance<T: Config> = StorageNMap<121 Key = (122 Key<Twox64Concat, CollectionId>,123 Key<Blake2_128Concat, T::CrossAccountId>,124 ),125 Value = u32,126 QueryKind = ValueQuery,127 >;128129 #[pallet::storage]130 pub type Allowance<T: Config> = StorageNMap<131 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),132 Value = T::CrossAccountId,133 QueryKind = OptionQuery,134 >;135}136137pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);138impl<T: Config> NonfungibleHandle<T> {139 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {140 Self(inner)141 }142 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {143 self.0144 }145}146impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {147 fn recorder(&self) -> &SubstrateRecorder<T> {148 self.0.recorder()149 }150 fn into_recorder(self) -> SubstrateRecorder<T> {151 self.0.into_recorder()152 }153}154impl<T: Config> Deref for NonfungibleHandle<T> {155 type Target = pallet_common::CollectionHandle<T>;156157 fn deref(&self) -> &Self::Target {158 &self.0159 }160}161162impl<T: Config> Pallet<T> {163 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {164 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)165 }166 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {167 <TokenData<T>>::contains_key((collection.id, token))168 }169}170171// unchecked calls skips any permission checks172impl<T: Config> Pallet<T> {173 pub fn init_collection(174 owner: T::AccountId,175 data: CreateCollectionData<T::AccountId>,176 ) -> Result<CollectionId, DispatchError> {177 <PalletCommon<T>>::init_collection(owner, data)178 }179 pub fn destroy_collection(180 collection: NonfungibleHandle<T>,181 sender: &T::CrossAccountId,182 ) -> DispatchResult {183 let id = collection.id;184185 // =========186187 PalletCommon::destroy_collection(collection.0, sender)?;188189 <TokenData<T>>::remove_prefix((id,), None);190 <Owned<T>>::remove_prefix((id,), None);191 <TokensMinted<T>>::remove(id);192 <TokensBurnt<T>>::remove(id);193 <Allowance<T>>::remove_prefix((id,), None);194 <AccountBalance<T>>::remove_prefix((id,), None);195 Ok(())196 }197198 pub fn burn(199 collection: &NonfungibleHandle<T>,200 sender: &T::CrossAccountId,201 token: TokenId,202 ) -> DispatchResult {203 let token_data =204 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;205 ensure!(206 &token_data.owner == sender207 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),208 <CommonError<T>>::NoPermission209 );210211 if collection.access == AccessMode::AllowList {212 collection.check_allowlist(sender)?;213 }214215 let burnt = <TokensBurnt<T>>::get(collection.id)216 .checked_add(1)217 .ok_or(ArithmeticError::Overflow)?;218219 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))220 .checked_sub(1)221 .ok_or(ArithmeticError::Overflow)?;222223 if balance == 0 {224 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));225 } else {226 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);227 }228 // =========229230 <Owned<T>>::remove((collection.id, &token_data.owner, token));231 <TokensBurnt<T>>::insert(collection.id, burnt);232 <TokenData<T>>::remove((collection.id, token));233 let old_spender = <Allowance<T>>::take((collection.id, token));234235 if let Some(old_spender) = old_spender {236 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(237 collection.id,238 token,239 sender.clone(),240 old_spender,241 0,242 ));243 }244245 collection.log_mirrored(ERC721Events::Transfer {246 from: *token_data.owner.as_eth(),247 to: H160::default(),248 token_id: token.into(),249 });250 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(251 collection.id,252 token,253 token_data.owner,254 1,255 ));256 Ok(())257 }258259 pub fn set_token_property(260 collection: &NonfungibleHandle<T>,261 sender: &T::CrossAccountId,262 token_id: TokenId,263 property: Property,264 ) -> DispatchResult {265 Self::check_token_change_permission(collection, sender, token_id, &property.key)?;266267 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {268 properties.try_set_property(property.clone())269 })270 .map_err(|e| -> CommonError<T> { e.into() })?;271272 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(273 collection.id,274 token_id,275 property,276 ));277278 Ok(())279 }280281 pub fn set_token_properties(282 collection: &NonfungibleHandle<T>,283 sender: &T::CrossAccountId,284 token_id: TokenId,285 properties: Vec<Property>,286 ) -> DispatchResult {287 for property in properties {288 Self::set_token_property(collection, sender, token_id, property)?;289 }290291 Ok(())292 }293294 pub fn delete_token_property(295 collection: &NonfungibleHandle<T>,296 sender: &T::CrossAccountId,297 token_id: TokenId,298 property_key: PropertyKey,299 ) -> DispatchResult {300 Self::check_token_change_permission(collection, sender, token_id, &property_key)?;301302 <TokenProperties<T>>::mutate((collection.id, token_id), |properties| {303 properties.remove_property(&property_key);304 });305306 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(307 collection.id,308 token_id,309 property_key,310 ));311312 Ok(())313 }314315 fn check_token_change_permission(316 collection: &NonfungibleHandle<T>,317 sender: &T::CrossAccountId,318 token_id: TokenId,319 property_key: &PropertyKey,320 ) -> DispatchResult {321 let permission = <PalletCommon<T>>::property_permissions(collection.id)322 .get(property_key)323 .map(|p| p.clone())324 .unwrap_or(PropertyPermission::none());325326 let token_data = <TokenData<T>>::get((collection.id, token_id))327 .ok_or(<CommonError<T>>::TokenNotFound)?;328329 let check_token_owner = || -> DispatchResult {330 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);331 Ok(())332 };333334 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))335 .get_property(property_key)336 .is_some();337338 match permission {339 PropertyPermission { mutable: false, .. } if is_property_exists => {340 Err(<CommonError<T>>::NoPermission.into())341 }342343 PropertyPermission {344 collection_admin,345 token_owner,346 ..347 } => {348 let mut check_result = Err(<CommonError<T>>::NoPermission.into());349350 if collection_admin {351 check_result = collection.check_is_owner_or_admin(sender);352 }353354 if token_owner {355 check_result.or(check_token_owner())356 } else {357 check_result358 }359 }360 }361 }362363 pub fn delete_token_properties(364 collection: &NonfungibleHandle<T>,365 sender: &T::CrossAccountId,366 token_id: TokenId,367 property_keys: Vec<PropertyKey>,368 ) -> DispatchResult {369 for key in property_keys {370 Self::delete_token_property(collection, sender, token_id, key)?;371 }372373 Ok(())374 }375376 pub fn set_collection_properties(377 collection: &NonfungibleHandle<T>,378 sender: &T::CrossAccountId,379 properties: Vec<Property>,380 ) -> DispatchResult {381 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)382 }383384 pub fn delete_collection_properties(385 collection: &CollectionHandle<T>,386 sender: &T::CrossAccountId,387 property_keys: Vec<PropertyKey>,388 ) -> DispatchResult {389 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)390 }391392 pub fn set_property_permissions(393 collection: &CollectionHandle<T>,394 sender: &T::CrossAccountId,395 property_permissions: Vec<PropertyKeyPermission>,396 ) -> DispatchResult {397 <PalletCommon<T>>::set_property_permissions(collection, sender, property_permissions)398 }399400 pub fn transfer(401 collection: &NonfungibleHandle<T>,402 from: &T::CrossAccountId,403 to: &T::CrossAccountId,404 token: TokenId,405 nesting_budget: &dyn Budget,406 ) -> DispatchResult {407 ensure!(408 collection.limits.transfers_enabled(),409 <CommonError<T>>::TransferNotAllowed410 );411412 let token_data =413 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;414 // TODO: require sender to be token, owner, require admins to go through transfer_from415 ensure!(416 &token_data.owner == from417 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),418 <CommonError<T>>::NoPermission419 );420421 if collection.access == AccessMode::AllowList {422 collection.check_allowlist(from)?;423 collection.check_allowlist(to)?;424 }425 <PalletCommon<T>>::ensure_correct_receiver(to)?;426427 let balance_from = <AccountBalance<T>>::get((collection.id, from))428 .checked_sub(1)429 .ok_or(<CommonError<T>>::TokenValueTooLow)?;430 let balance_to = if from != to {431 let balance_to = <AccountBalance<T>>::get((collection.id, to))432 .checked_add(1)433 .ok_or(ArithmeticError::Overflow)?;434435 ensure!(436 balance_to < collection.limits.account_token_ownership_limit(),437 <CommonError<T>>::AccountTokenLimitExceeded,438 );439440 Some(balance_to)441 } else {442 None443 };444445 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {446 let handle = <CollectionHandle<T>>::try_get(target.0)?;447 let dispatch = T::CollectionDispatch::dispatch(handle);448 let dispatch = dispatch.as_dyn();449450 dispatch.check_nesting(451 from.clone(),452 (collection.id, token),453 target.1,454 nesting_budget,455 )?;456 }457458 // =========459460 <TokenData<T>>::insert(461 (collection.id, token),462 ItemData {463 owner: to.clone(),464 ..token_data465 },466 );467468 if let Some(balance_to) = balance_to {469 // from != to470 if balance_from == 0 {471 <AccountBalance<T>>::remove((collection.id, from));472 } else {473 <AccountBalance<T>>::insert((collection.id, from), balance_from);474 }475 <AccountBalance<T>>::insert((collection.id, to), balance_to);476 <Owned<T>>::remove((collection.id, from, token));477 <Owned<T>>::insert((collection.id, to, token), true);478 }479 Self::set_allowance_unchecked(collection, from, token, None, true);480481 collection.log_mirrored(ERC721Events::Transfer {482 from: *from.as_eth(),483 to: *to.as_eth(),484 token_id: token.into(),485 });486 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(487 collection.id,488 token,489 from.clone(),490 to.clone(),491 1,492 ));493 Ok(())494 }495496 pub fn create_multiple_items(497 collection: &NonfungibleHandle<T>,498 sender: &T::CrossAccountId,499 data: Vec<CreateItemData<T>>,500 nesting_budget: &dyn Budget,501 ) -> DispatchResult {502 if !collection.is_owner_or_admin(sender) {503 ensure!(504 collection.mint_mode,505 <CommonError<T>>::PublicMintingNotAllowed506 );507 collection.check_allowlist(sender)?;508509 for item in data.iter() {510 collection.check_allowlist(&item.owner)?;511 }512 }513514 for data in data.iter() {515 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;516 }517518 let first_token = <TokensMinted<T>>::get(collection.id);519 let tokens_minted = first_token520 .checked_add(data.len() as u32)521 .ok_or(ArithmeticError::Overflow)?;522 ensure!(523 tokens_minted <= collection.limits.token_limit(),524 <CommonError<T>>::CollectionTokenLimitExceeded525 );526527 let mut balances = BTreeMap::new();528 for data in &data {529 let balance = balances530 .entry(&data.owner)531 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));532 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;533534 ensure!(535 *balance <= collection.limits.account_token_ownership_limit(),536 <CommonError<T>>::AccountTokenLimitExceeded,537 );538 }539540 for (i, data) in data.iter().enumerate() {541 let token = TokenId(first_token + i as u32 + 1);542 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {543 let handle = <CollectionHandle<T>>::try_get(target.0)?;544 let dispatch = T::CollectionDispatch::dispatch(handle);545 let dispatch = dispatch.as_dyn();546 dispatch.check_nesting(547 sender.clone(),548 (collection.id, token),549 target.1,550 nesting_budget,551 )?;552 }553 }554555 // =========556557 <TokensMinted<T>>::insert(collection.id, tokens_minted);558 for (account, balance) in balances {559 <AccountBalance<T>>::insert((collection.id, account), balance);560 }561 for (i, data) in data.into_iter().enumerate() {562 let token = first_token + i as u32 + 1;563564 <TokenData<T>>::insert(565 (collection.id, token),566 ItemData {567 const_data: data.const_data,568 variable_data: data.variable_data,569 owner: data.owner.clone(),570 },571 );572 <Owned<T>>::insert((collection.id, &data.owner, token), true);573574 Self::set_token_properties(575 collection,576 sender,577 TokenId(token),578 data.properties.into_inner(),579 )?;580581 collection.log_mirrored(ERC721Events::Transfer {582 from: H160::default(),583 to: *data.owner.as_eth(),584 token_id: token.into(),585 });586 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(587 collection.id,588 TokenId(token),589 data.owner.clone(),590 1,591 ));592 }593 Ok(())594 }595596 pub fn set_allowance_unchecked(597 collection: &NonfungibleHandle<T>,598 sender: &T::CrossAccountId,599 token: TokenId,600 spender: Option<&T::CrossAccountId>,601 assume_implicit_eth: bool,602 ) {603 if let Some(spender) = spender {604 let old_spender = <Allowance<T>>::get((collection.id, token));605 <Allowance<T>>::insert((collection.id, token), spender);606 // In ERC721 there is only one possible approved user of token, so we set607 // approved user to spender608 collection.log_mirrored(ERC721Events::Approval {609 owner: *sender.as_eth(),610 approved: *spender.as_eth(),611 token_id: token.into(),612 });613 // In Unique chain, any token can have any amount of approved users, so we need to614 // set allowance of old owner to 0, and allowance of new owner to 1615 if old_spender.as_ref() != Some(spender) {616 if let Some(old_owner) = old_spender {617 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(618 collection.id,619 token,620 sender.clone(),621 old_owner,622 0,623 ));624 }625 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(626 collection.id,627 token,628 sender.clone(),629 spender.clone(),630 1,631 ));632 }633 } else {634 let old_spender = <Allowance<T>>::take((collection.id, token));635 if !assume_implicit_eth {636 // In ERC721 there is only one possible approved user of token, so we set637 // approved user to zero address638 collection.log_mirrored(ERC721Events::Approval {639 owner: *sender.as_eth(),640 approved: H160::default(),641 token_id: token.into(),642 });643 }644 // In Unique chain, any token can have any amount of approved users, so we need to645 // set allowance of old owner to 0646 if let Some(old_spender) = old_spender {647 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(648 collection.id,649 token,650 sender.clone(),651 old_spender,652 0,653 ));654 }655 }656 }657658 pub fn set_allowance(659 collection: &NonfungibleHandle<T>,660 sender: &T::CrossAccountId,661 token: TokenId,662 spender: Option<&T::CrossAccountId>,663 ) -> DispatchResult {664 if collection.access == AccessMode::AllowList {665 collection.check_allowlist(sender)?;666 if let Some(spender) = spender {667 collection.check_allowlist(spender)?;668 }669 }670671 if let Some(spender) = spender {672 <PalletCommon<T>>::ensure_correct_receiver(spender)?;673 }674 let token_data =675 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;676 if &token_data.owner != sender {677 ensure!(678 collection.ignores_owned_amount(sender),679 <CommonError<T>>::CantApproveMoreThanOwned680 );681 }682683 // =========684685 Self::set_allowance_unchecked(collection, sender, token, spender, false);686 Ok(())687 }688689 fn check_allowed(690 collection: &NonfungibleHandle<T>,691 spender: &T::CrossAccountId,692 from: &T::CrossAccountId,693 token: TokenId,694 nesting_budget: &dyn Budget,695 ) -> DispatchResult {696 if spender.conv_eq(from) {697 return Ok(());698 }699 if collection.access == AccessMode::AllowList {700 // `from`, `to` checked in [`transfer`]701 collection.check_allowlist(spender)?;702 }703 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {704 // TODO: should collection owner be allowed to perform this transfer?705 ensure!(706 <PalletStructure<T>>::check_indirectly_owned(707 spender.clone(),708 source.0,709 source.1,710 None,711 nesting_budget712 )?,713 <CommonError<T>>::ApprovedValueTooLow,714 );715 return Ok(());716 }717 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {718 return Ok(());719 }720 ensure!(721 collection.ignores_allowance(spender),722 <CommonError<T>>::ApprovedValueTooLow723 );724 Ok(())725 }726727 pub fn transfer_from(728 collection: &NonfungibleHandle<T>,729 spender: &T::CrossAccountId,730 from: &T::CrossAccountId,731 to: &T::CrossAccountId,732 token: TokenId,733 nesting_budget: &dyn Budget,734 ) -> DispatchResult {735 Self::check_allowed(collection, spender, from, token, nesting_budget)?;736737 // =========738739 // Allowance is reset in [`transfer`]740 Self::transfer(collection, from, to, token, nesting_budget)741 }742743 pub fn burn_from(744 collection: &NonfungibleHandle<T>,745 spender: &T::CrossAccountId,746 from: &T::CrossAccountId,747 token: TokenId,748 nesting_budget: &dyn Budget,749 ) -> DispatchResult {750 Self::check_allowed(collection, spender, from, token, nesting_budget)?;751752 // =========753754 Self::burn(collection, from, token)755 }756757 pub fn set_variable_metadata(758 collection: &NonfungibleHandle<T>,759 sender: &T::CrossAccountId,760 token: TokenId,761 data: BoundedVec<u8, CustomDataLimit>,762 ) -> DispatchResult {763 let token_data =764 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;765 collection.check_can_update_meta(sender, &token_data.owner)?;766767 // =========768769 <TokenData<T>>::insert(770 (collection.id, token),771 ItemData {772 variable_data: data,773 ..token_data774 },775 );776 Ok(())777 }778779 pub fn check_nesting(780 handle: &NonfungibleHandle<T>,781 sender: T::CrossAccountId,782 from: (CollectionId, TokenId),783 under: TokenId,784 nesting_budget: &dyn Budget,785 ) -> DispatchResult {786 fn ensure_sender_allowed<T: Config>(787 collection: CollectionId,788 token: TokenId,789 for_nest: (CollectionId, TokenId),790 sender: T::CrossAccountId,791 budget: &dyn Budget,792 ) -> DispatchResult {793 ensure!(794 <PalletStructure<T>>::check_indirectly_owned(795 sender,796 collection,797 token,798 Some(for_nest),799 budget800 )?,801 <CommonError<T>>::OnlyOwnerAllowedToNest,802 );803 Ok(())804 }805 match handle.limits.nesting_rule() {806 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),807 NestingRule::Owner => {808 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?809 }810 NestingRule::OwnerRestricted(whitelist) => {811 ensure!(812 whitelist.contains(&from.0),813 <CommonError<T>>::SourceCollectionIsNotAllowedToNest814 );815 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?816 }817 }818 Ok(())819 }820821 /// Delegated to `create_multiple_items`822 pub fn create_item(823 collection: &NonfungibleHandle<T>,824 sender: &T::CrossAccountId,825 data: CreateItemData<T>,826 nesting_budget: &dyn Budget,827 ) -> DispatchResult {828 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)829 }830}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use erc::ERC721Events;20use frame_support::{BoundedVec, ensure, fail};21use up_data_structs::{22 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,23 mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,24 PropertyKey, PropertyKeyPermission, Properties, TrySet,25};26use pallet_evm::account::CrossAccountId;27use pallet_common::{28 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,29 dispatch::CollectionDispatch,30};31use pallet_structure::Pallet as PalletStructure;32use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};33use sp_core::H160;34use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};35use sp_std::{vec::Vec, vec};36use core::ops::Deref;37use sp_std::collections::btree_map::BTreeMap;38use codec::{Encode, Decode, MaxEncodedLen};39use scale_info::TypeInfo;4041pub use pallet::*;42#[cfg(feature = "runtime-benchmarks")]43pub mod benchmarking;44pub mod common;45pub mod erc;46pub mod weights;4748pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;49pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;5051#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]52pub struct ItemData<CrossAccountId> {53 pub const_data: BoundedVec<u8, CustomDataLimit>,54 pub variable_data: BoundedVec<u8, CustomDataLimit>,55 pub owner: CrossAccountId,56}5758#[frame_support::pallet]59pub mod pallet {60 use super::*;61 use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};62 use up_data_structs::{CollectionId, TokenId};63 use super::weights::WeightInfo;6465 #[pallet::error]66 pub enum Error<T> {67 /// Not Nonfungible item data used to mint in Nonfungible collection.68 NotNonfungibleDataUsedToMintFungibleCollectionToken,69 /// Used amount > 1 with NFT70 NonfungibleItemsHaveNoAmount,71 }7273 #[pallet::config]74 pub trait Config:75 frame_system::Config + pallet_common::Config + pallet_structure::Config76 {77 type WeightInfo: WeightInfo;78 }7980 #[pallet::pallet]81 #[pallet::generate_store(pub(super) trait Store)]82 pub struct Pallet<T>(_);8384 #[pallet::storage]85 pub type TokensMinted<T: Config> =86 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;87 #[pallet::storage]88 pub type TokensBurnt<T: Config> =89 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;9091 #[pallet::storage]92 pub type TokenData<T: Config> = StorageNMap<93 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),94 Value = ItemData<T::CrossAccountId>,95 QueryKind = OptionQuery,96 >;9798 #[pallet::storage]99 #[pallet::getter(fn token_properties)]100 pub type TokenProperties<T: Config> = StorageNMap<101 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),102 Value = Properties,103 QueryKind = ValueQuery,104 OnEmpty = up_data_structs::TokenProperties,105 >;106107 /// Used to enumerate tokens owned by account108 #[pallet::storage]109 pub type Owned<T: Config> = StorageNMap<110 Key = (111 Key<Twox64Concat, CollectionId>,112 Key<Blake2_128Concat, T::CrossAccountId>,113 Key<Twox64Concat, TokenId>,114 ),115 Value = bool,116 QueryKind = ValueQuery,117 >;118119 #[pallet::storage]120 pub type AccountBalance<T: Config> = StorageNMap<121 Key = (122 Key<Twox64Concat, CollectionId>,123 Key<Blake2_128Concat, T::CrossAccountId>,124 ),125 Value = u32,126 QueryKind = ValueQuery,127 >;128129 #[pallet::storage]130 pub type Allowance<T: Config> = StorageNMap<131 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),132 Value = T::CrossAccountId,133 QueryKind = OptionQuery,134 >;135}136137pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);138impl<T: Config> NonfungibleHandle<T> {139 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {140 Self(inner)141 }142 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {143 self.0144 }145}146impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {147 fn recorder(&self) -> &SubstrateRecorder<T> {148 self.0.recorder()149 }150 fn into_recorder(self) -> SubstrateRecorder<T> {151 self.0.into_recorder()152 }153}154impl<T: Config> Deref for NonfungibleHandle<T> {155 type Target = pallet_common::CollectionHandle<T>;156157 fn deref(&self) -> &Self::Target {158 &self.0159 }160}161162impl<T: Config> Pallet<T> {163 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {164 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)165 }166 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {167 <TokenData<T>>::contains_key((collection.id, token))168 }169}170171// unchecked calls skips any permission checks172impl<T: Config> Pallet<T> {173 pub fn init_collection(174 owner: T::AccountId,175 data: CreateCollectionData<T::AccountId>,176 ) -> Result<CollectionId, DispatchError> {177 <PalletCommon<T>>::init_collection(owner, data)178 }179 pub fn destroy_collection(180 collection: NonfungibleHandle<T>,181 sender: &T::CrossAccountId,182 ) -> DispatchResult {183 let id = collection.id;184185 // =========186187 PalletCommon::destroy_collection(collection.0, sender)?;188189 <TokenData<T>>::remove_prefix((id,), None);190 <Owned<T>>::remove_prefix((id,), None);191 <TokensMinted<T>>::remove(id);192 <TokensBurnt<T>>::remove(id);193 <Allowance<T>>::remove_prefix((id,), None);194 <AccountBalance<T>>::remove_prefix((id,), None);195 Ok(())196 }197198 pub fn burn(199 collection: &NonfungibleHandle<T>,200 sender: &T::CrossAccountId,201 token: TokenId,202 ) -> DispatchResult {203 let token_data =204 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;205 ensure!(206 &token_data.owner == sender207 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),208 <CommonError<T>>::NoPermission209 );210211 if collection.access == AccessMode::AllowList {212 collection.check_allowlist(sender)?;213 }214215 let burnt = <TokensBurnt<T>>::get(collection.id)216 .checked_add(1)217 .ok_or(ArithmeticError::Overflow)?;218219 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))220 .checked_sub(1)221 .ok_or(ArithmeticError::Overflow)?;222223 if balance == 0 {224 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));225 } else {226 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);227 }228 // =========229230 <Owned<T>>::remove((collection.id, &token_data.owner, token));231 <TokensBurnt<T>>::insert(collection.id, burnt);232 <TokenData<T>>::remove((collection.id, token));233 let old_spender = <Allowance<T>>::take((collection.id, token));234235 if let Some(old_spender) = old_spender {236 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(237 collection.id,238 token,239 sender.clone(),240 old_spender,241 0,242 ));243 }244245 collection.log_mirrored(ERC721Events::Transfer {246 from: *token_data.owner.as_eth(),247 to: H160::default(),248 token_id: token.into(),249 });250 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(251 collection.id,252 token,253 token_data.owner,254 1,255 ));256 Ok(())257 }258259 pub fn set_token_property(260 collection: &NonfungibleHandle<T>,261 sender: &T::CrossAccountId,262 token_id: TokenId,263 property: Property,264 ) -> DispatchResult {265 Self::check_token_change_permission(collection, sender, token_id, &property.key)?;266267 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {268 let property = property.clone();269 properties.try_set(property.key, property.value)270 })271 .map_err(|e| -> CommonError<T> { e.into() })?;272273 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(274 collection.id,275 token_id,276 property,277 ));278279 Ok(())280 }281282 pub fn set_token_properties(283 collection: &NonfungibleHandle<T>,284 sender: &T::CrossAccountId,285 token_id: TokenId,286 properties: Vec<Property>,287 ) -> DispatchResult {288 for property in properties {289 Self::set_token_property(collection, sender, token_id, property)?;290 }291292 Ok(())293 }294295 pub fn delete_token_property(296 collection: &NonfungibleHandle<T>,297 sender: &T::CrossAccountId,298 token_id: TokenId,299 property_key: PropertyKey,300 ) -> DispatchResult {301 Self::check_token_change_permission(collection, sender, token_id, &property_key)?;302303 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {304 properties.remove(&property_key)305 }).map_err(|e| -> CommonError<T> { e.into() })?;306307 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(308 collection.id,309 token_id,310 property_key,311 ));312313 Ok(())314 }315316 fn check_token_change_permission(317 collection: &NonfungibleHandle<T>,318 sender: &T::CrossAccountId,319 token_id: TokenId,320 property_key: &PropertyKey,321 ) -> DispatchResult {322 let permission = <PalletCommon<T>>::property_permissions(collection.id)323 .get(property_key)324 .map(|p| p.clone())325 .unwrap_or(PropertyPermission::none());326327 let token_data = <TokenData<T>>::get((collection.id, token_id))328 .ok_or(<CommonError<T>>::TokenNotFound)?;329330 let check_token_owner = || -> DispatchResult {331 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);332 Ok(())333 };334335 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))336 .get(property_key)337 .is_some();338339 match permission {340 PropertyPermission { mutable: false, .. } if is_property_exists => {341 Err(<CommonError<T>>::NoPermission.into())342 }343344 PropertyPermission {345 collection_admin,346 token_owner,347 ..348 } => {349 let mut check_result = Err(<CommonError<T>>::NoPermission.into());350351 if collection_admin {352 check_result = collection.check_is_owner_or_admin(sender);353 }354355 if token_owner {356 check_result.or(check_token_owner())357 } else {358 check_result359 }360 }361 }362 }363364 pub fn delete_token_properties(365 collection: &NonfungibleHandle<T>,366 sender: &T::CrossAccountId,367 token_id: TokenId,368 property_keys: Vec<PropertyKey>,369 ) -> DispatchResult {370 for key in property_keys {371 Self::delete_token_property(collection, sender, token_id, key)?;372 }373374 Ok(())375 }376377 pub fn set_collection_properties(378 collection: &NonfungibleHandle<T>,379 sender: &T::CrossAccountId,380 properties: Vec<Property>,381 ) -> DispatchResult {382 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)383 }384385 pub fn delete_collection_properties(386 collection: &CollectionHandle<T>,387 sender: &T::CrossAccountId,388 property_keys: Vec<PropertyKey>,389 ) -> DispatchResult {390 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)391 }392393 pub fn set_property_permissions(394 collection: &CollectionHandle<T>,395 sender: &T::CrossAccountId,396 property_permissions: Vec<PropertyKeyPermission>,397 ) -> DispatchResult {398 <PalletCommon<T>>::set_property_permissions(collection, sender, property_permissions)399 }400401 pub fn transfer(402 collection: &NonfungibleHandle<T>,403 from: &T::CrossAccountId,404 to: &T::CrossAccountId,405 token: TokenId,406 nesting_budget: &dyn Budget,407 ) -> DispatchResult {408 ensure!(409 collection.limits.transfers_enabled(),410 <CommonError<T>>::TransferNotAllowed411 );412413 let token_data =414 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;415 // TODO: require sender to be token, owner, require admins to go through transfer_from416 ensure!(417 &token_data.owner == from418 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),419 <CommonError<T>>::NoPermission420 );421422 if collection.access == AccessMode::AllowList {423 collection.check_allowlist(from)?;424 collection.check_allowlist(to)?;425 }426 <PalletCommon<T>>::ensure_correct_receiver(to)?;427428 let balance_from = <AccountBalance<T>>::get((collection.id, from))429 .checked_sub(1)430 .ok_or(<CommonError<T>>::TokenValueTooLow)?;431 let balance_to = if from != to {432 let balance_to = <AccountBalance<T>>::get((collection.id, to))433 .checked_add(1)434 .ok_or(ArithmeticError::Overflow)?;435436 ensure!(437 balance_to < collection.limits.account_token_ownership_limit(),438 <CommonError<T>>::AccountTokenLimitExceeded,439 );440441 Some(balance_to)442 } else {443 None444 };445446 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {447 let handle = <CollectionHandle<T>>::try_get(target.0)?;448 let dispatch = T::CollectionDispatch::dispatch(handle);449 let dispatch = dispatch.as_dyn();450451 dispatch.check_nesting(452 from.clone(),453 (collection.id, token),454 target.1,455 nesting_budget,456 )?;457 }458459 // =========460461 <TokenData<T>>::insert(462 (collection.id, token),463 ItemData {464 owner: to.clone(),465 ..token_data466 },467 );468469 if let Some(balance_to) = balance_to {470 // from != to471 if balance_from == 0 {472 <AccountBalance<T>>::remove((collection.id, from));473 } else {474 <AccountBalance<T>>::insert((collection.id, from), balance_from);475 }476 <AccountBalance<T>>::insert((collection.id, to), balance_to);477 <Owned<T>>::remove((collection.id, from, token));478 <Owned<T>>::insert((collection.id, to, token), true);479 }480 Self::set_allowance_unchecked(collection, from, token, None, true);481482 collection.log_mirrored(ERC721Events::Transfer {483 from: *from.as_eth(),484 to: *to.as_eth(),485 token_id: token.into(),486 });487 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(488 collection.id,489 token,490 from.clone(),491 to.clone(),492 1,493 ));494 Ok(())495 }496497 pub fn create_multiple_items(498 collection: &NonfungibleHandle<T>,499 sender: &T::CrossAccountId,500 data: Vec<CreateItemData<T>>,501 nesting_budget: &dyn Budget,502 ) -> DispatchResult {503 if !collection.is_owner_or_admin(sender) {504 ensure!(505 collection.mint_mode,506 <CommonError<T>>::PublicMintingNotAllowed507 );508 collection.check_allowlist(sender)?;509510 for item in data.iter() {511 collection.check_allowlist(&item.owner)?;512 }513 }514515 for data in data.iter() {516 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;517 }518519 let first_token = <TokensMinted<T>>::get(collection.id);520 let tokens_minted = first_token521 .checked_add(data.len() as u32)522 .ok_or(ArithmeticError::Overflow)?;523 ensure!(524 tokens_minted <= collection.limits.token_limit(),525 <CommonError<T>>::CollectionTokenLimitExceeded526 );527528 let mut balances = BTreeMap::new();529 for data in &data {530 let balance = balances531 .entry(&data.owner)532 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));533 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;534535 ensure!(536 *balance <= collection.limits.account_token_ownership_limit(),537 <CommonError<T>>::AccountTokenLimitExceeded,538 );539 }540541 for (i, data) in data.iter().enumerate() {542 let token = TokenId(first_token + i as u32 + 1);543 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {544 let handle = <CollectionHandle<T>>::try_get(target.0)?;545 let dispatch = T::CollectionDispatch::dispatch(handle);546 let dispatch = dispatch.as_dyn();547 dispatch.check_nesting(548 sender.clone(),549 (collection.id, token),550 target.1,551 nesting_budget,552 )?;553 }554 }555556 // =========557558 <TokensMinted<T>>::insert(collection.id, tokens_minted);559 for (account, balance) in balances {560 <AccountBalance<T>>::insert((collection.id, account), balance);561 }562 for (i, data) in data.into_iter().enumerate() {563 let token = first_token + i as u32 + 1;564565 <TokenData<T>>::insert(566 (collection.id, token),567 ItemData {568 const_data: data.const_data,569 variable_data: data.variable_data,570 owner: data.owner.clone(),571 },572 );573 <Owned<T>>::insert((collection.id, &data.owner, token), true);574575 Self::set_token_properties(576 collection,577 sender,578 TokenId(token),579 data.properties.into_inner(),580 )?;581582 collection.log_mirrored(ERC721Events::Transfer {583 from: H160::default(),584 to: *data.owner.as_eth(),585 token_id: token.into(),586 });587 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(588 collection.id,589 TokenId(token),590 data.owner.clone(),591 1,592 ));593 }594 Ok(())595 }596597 pub fn set_allowance_unchecked(598 collection: &NonfungibleHandle<T>,599 sender: &T::CrossAccountId,600 token: TokenId,601 spender: Option<&T::CrossAccountId>,602 assume_implicit_eth: bool,603 ) {604 if let Some(spender) = spender {605 let old_spender = <Allowance<T>>::get((collection.id, token));606 <Allowance<T>>::insert((collection.id, token), spender);607 // In ERC721 there is only one possible approved user of token, so we set608 // approved user to spender609 collection.log_mirrored(ERC721Events::Approval {610 owner: *sender.as_eth(),611 approved: *spender.as_eth(),612 token_id: token.into(),613 });614 // In Unique chain, any token can have any amount of approved users, so we need to615 // set allowance of old owner to 0, and allowance of new owner to 1616 if old_spender.as_ref() != Some(spender) {617 if let Some(old_owner) = old_spender {618 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(619 collection.id,620 token,621 sender.clone(),622 old_owner,623 0,624 ));625 }626 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(627 collection.id,628 token,629 sender.clone(),630 spender.clone(),631 1,632 ));633 }634 } else {635 let old_spender = <Allowance<T>>::take((collection.id, token));636 if !assume_implicit_eth {637 // In ERC721 there is only one possible approved user of token, so we set638 // approved user to zero address639 collection.log_mirrored(ERC721Events::Approval {640 owner: *sender.as_eth(),641 approved: H160::default(),642 token_id: token.into(),643 });644 }645 // In Unique chain, any token can have any amount of approved users, so we need to646 // set allowance of old owner to 0647 if let Some(old_spender) = old_spender {648 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(649 collection.id,650 token,651 sender.clone(),652 old_spender,653 0,654 ));655 }656 }657 }658659 pub fn set_allowance(660 collection: &NonfungibleHandle<T>,661 sender: &T::CrossAccountId,662 token: TokenId,663 spender: Option<&T::CrossAccountId>,664 ) -> DispatchResult {665 if collection.access == AccessMode::AllowList {666 collection.check_allowlist(sender)?;667 if let Some(spender) = spender {668 collection.check_allowlist(spender)?;669 }670 }671672 if let Some(spender) = spender {673 <PalletCommon<T>>::ensure_correct_receiver(spender)?;674 }675 let token_data =676 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;677 if &token_data.owner != sender {678 ensure!(679 collection.ignores_owned_amount(sender),680 <CommonError<T>>::CantApproveMoreThanOwned681 );682 }683684 // =========685686 Self::set_allowance_unchecked(collection, sender, token, spender, false);687 Ok(())688 }689690 fn check_allowed(691 collection: &NonfungibleHandle<T>,692 spender: &T::CrossAccountId,693 from: &T::CrossAccountId,694 token: TokenId,695 nesting_budget: &dyn Budget,696 ) -> DispatchResult {697 if spender.conv_eq(from) {698 return Ok(());699 }700 if collection.access == AccessMode::AllowList {701 // `from`, `to` checked in [`transfer`]702 collection.check_allowlist(spender)?;703 }704 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {705 // TODO: should collection owner be allowed to perform this transfer?706 ensure!(707 <PalletStructure<T>>::check_indirectly_owned(708 spender.clone(),709 source.0,710 source.1,711 None,712 nesting_budget713 )?,714 <CommonError<T>>::ApprovedValueTooLow,715 );716 return Ok(());717 }718 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {719 return Ok(());720 }721 ensure!(722 collection.ignores_allowance(spender),723 <CommonError<T>>::ApprovedValueTooLow724 );725 Ok(())726 }727728 pub fn transfer_from(729 collection: &NonfungibleHandle<T>,730 spender: &T::CrossAccountId,731 from: &T::CrossAccountId,732 to: &T::CrossAccountId,733 token: TokenId,734 nesting_budget: &dyn Budget,735 ) -> DispatchResult {736 Self::check_allowed(collection, spender, from, token, nesting_budget)?;737738 // =========739740 // Allowance is reset in [`transfer`]741 Self::transfer(collection, from, to, token, nesting_budget)742 }743744 pub fn burn_from(745 collection: &NonfungibleHandle<T>,746 spender: &T::CrossAccountId,747 from: &T::CrossAccountId,748 token: TokenId,749 nesting_budget: &dyn Budget,750 ) -> DispatchResult {751 Self::check_allowed(collection, spender, from, token, nesting_budget)?;752753 // =========754755 Self::burn(collection, from, token)756 }757758 pub fn set_variable_metadata(759 collection: &NonfungibleHandle<T>,760 sender: &T::CrossAccountId,761 token: TokenId,762 data: BoundedVec<u8, CustomDataLimit>,763 ) -> DispatchResult {764 let token_data =765 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;766 collection.check_can_update_meta(sender, &token_data.owner)?;767768 // =========769770 <TokenData<T>>::insert(771 (collection.id, token),772 ItemData {773 variable_data: data,774 ..token_data775 },776 );777 Ok(())778 }779780 pub fn check_nesting(781 handle: &NonfungibleHandle<T>,782 sender: T::CrossAccountId,783 from: (CollectionId, TokenId),784 under: TokenId,785 nesting_budget: &dyn Budget,786 ) -> DispatchResult {787 fn ensure_sender_allowed<T: Config>(788 collection: CollectionId,789 token: TokenId,790 for_nest: (CollectionId, TokenId),791 sender: T::CrossAccountId,792 budget: &dyn Budget,793 ) -> DispatchResult {794 ensure!(795 <PalletStructure<T>>::check_indirectly_owned(796 sender,797 collection,798 token,799 Some(for_nest),800 budget801 )?,802 <CommonError<T>>::OnlyOwnerAllowedToNest,803 );804 Ok(())805 }806 match handle.limits.nesting_rule() {807 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),808 NestingRule::Owner => {809 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?810 }811 NestingRule::OwnerRestricted(whitelist) => {812 ensure!(813 whitelist.contains(&from.0),814 <CommonError<T>>::SourceCollectionIsNotAllowedToNest815 );816 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?817 }818 }819 Ok(())820 }821822 /// Delegated to `create_multiple_items`823 pub fn create_item(824 collection: &NonfungibleHandle<T>,825 sender: &T::CrossAccountId,826 data: CreateItemData<T>,827 nesting_budget: &dyn Budget,828 ) -> DispatchResult {829 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)830 }831}primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -689,16 +689,82 @@
pub enum PropertiesError {
NoSpaceForProperty,
PropertyLimitReached,
+ InvalidCharacterInPropertyKey,
+}
+
+pub trait TrySet: Sized {
+ type Value;
+
+ fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError>;
+
+ fn try_set_from_iter<I>(&mut self, iter: I) -> Result<(), PropertiesError>
+ where
+ I: Iterator<Item=(PropertyKey, Self::Value)>
+ {
+ for (key, value) in iter {
+ self.try_set(key, value)?;
+ }
+
+ Ok(())
+ }
+}
+
+#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]
+#[derivative(Default(bound = ""))]
+pub struct PropertiesMap<Value>(BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>);
+
+impl<Value> PropertiesMap<Value> {
+ pub fn new() -> Self {
+ Self(BoundedBTreeMap::new())
+ }
+
+ pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {
+ Self::check_property_key(key)?;
+
+ Ok(self.0.remove(key))
+ }
+
+ pub fn get(&self, key: &PropertyKey) -> Option<&Value> {
+ self.0.get(key)
+ }
+
+ pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &Value)> {
+ self.0.iter()
+ }
+
+ fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {
+ let key_str = sp_std::str::from_utf8(key.as_slice())
+ .map_err(|_| PropertiesError::InvalidCharacterInPropertyKey)?;
+
+ for ch in key_str.chars() {
+ if !ch.is_ascii_alphanumeric() && ch != '_' && ch != '-' {
+ return Err(PropertiesError::InvalidCharacterInPropertyKey);
+ }
+ }
+
+ Ok(())
+ }
+}
+
+impl<Value> TrySet for PropertiesMap<Value> {
+ type Value = Value;
+
+ fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {
+ Self::check_property_key(&key)?;
+
+ self.0
+ .try_insert(key, value)
+ .map_err(|_| PropertiesError::PropertyLimitReached)?;
+
+ Ok(())
+ }
}
-pub type PropertiesMap =
- BoundedBTreeMap<PropertyKey, PropertyValue, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
-pub type PropertiesPermissionMap =
- BoundedBTreeMap<PropertyKey, PropertyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
+pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;
#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]
pub struct Properties {
- map: PropertiesMap,
+ map: PropertiesMap<PropertyValue>,
consumed_space: u32,
space_limit: u32,
}
@@ -706,57 +772,47 @@
impl Properties {
pub fn new(space_limit: u32) -> Self {
Self {
- map: BoundedBTreeMap::new(),
+ map: PropertiesMap::new(),
consumed_space: 0,
space_limit,
}
}
- pub fn from_collection_props_vec(
- data: CollectionPropertiesVec,
- ) -> Result<Self, PropertiesError> {
- let mut props = Self::new(MAX_COLLECTION_PROPERTIES_SIZE);
+ pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {
+ let value = self.map.remove(key)?;
- for property in data.into_iter() {
- props.try_set_property(property)?;
+ if let Some(ref value) = value {
+ let value_len = value.len() as u32;
+ self.consumed_space -= value_len;
}
- Ok(props)
+ Ok(value)
}
- pub fn try_set_property(&mut self, property: Property) -> Result<(), PropertiesError> {
- let value_len = property.value.len();
+ pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {
+ self.map.get(key)
+ }
+ pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {
+ self.map.iter()
+ }
+}
+
+impl TrySet for Properties {
+ type Value = PropertyValue;
+
+ fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {
+ let value_len = value.len();
+
if self.consumed_space as usize + value_len > self.space_limit as usize {
return Err(PropertiesError::NoSpaceForProperty);
}
- self.map
- .try_insert(property.key, property.value)
- .map_err(|_| PropertiesError::PropertyLimitReached)?;
+ self.map.try_set(key, value)?;
self.consumed_space += value_len as u32;
Ok(())
- }
-
- pub fn remove_property(&mut self, key: &PropertyKey) {
- let property = self.map.get(key);
-
- if let Some(value) = property {
- let value_len = value.len() as u32;
-
- self.map.remove(key);
- self.consumed_space -= value_len;
- }
- }
-
- pub fn get_property(&self, key: &PropertyKey) -> Option<&PropertyValue> {
- self.map.get(key)
- }
-
- pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {
- self.map.iter()
}
}