difftreelog
Change PropertyPermission
in: master
3 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -812,7 +812,7 @@
let current_permission = all_permissions.get(&property_permission.key);
if matches![
current_permission,
- Some(PropertyPermission::AdminConst | PropertyPermission::ItemOwnerConst)
+ Some(PropertyPermission { mutable: false, .. })
] {
return Err(<Error<T>>::NoPermission.into());
}
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,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 = up_data_structs::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, is_property_exists) {339 (PropertyPermission::AdminConst, false) => collection.check_is_owner_or_admin(sender),340 (PropertyPermission::Admin, _) => collection.check_is_owner_or_admin(sender),341 (PropertyPermission::ItemOwnerConst, false) => check_token_owner(),342 (PropertyPermission::ItemOwner, _) => check_token_owner(),343 (PropertyPermission::ItemOwnerOrAdmin, _) => {344 check_token_owner().or(collection.check_is_owner_or_admin(sender))345 }346 _ => Err(<CommonError<T>>::NoPermission.into()),347 }348 }349350 pub fn delete_token_properties(351 collection: &NonfungibleHandle<T>,352 sender: &T::CrossAccountId,353 token_id: TokenId,354 property_keys: Vec<PropertyKey>,355 ) -> DispatchResult {356 for key in property_keys {357 Self::delete_token_property(collection, sender, token_id, key)?;358 }359360 Ok(())361 }362363 pub fn set_collection_properties(364 collection: &NonfungibleHandle<T>,365 sender: &T::CrossAccountId,366 properties: Vec<Property>,367 ) -> DispatchResult {368 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)369 }370371 pub fn delete_collection_properties(372 collection: &CollectionHandle<T>,373 sender: &T::CrossAccountId,374 property_keys: Vec<PropertyKey>,375 ) -> DispatchResult {376 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)377 }378379 pub fn set_property_permissions(380 collection: &CollectionHandle<T>,381 sender: &T::CrossAccountId,382 property_permissions: Vec<PropertyKeyPermission>,383 ) -> DispatchResult {384 <PalletCommon<T>>::set_property_permissions(collection, sender, property_permissions)385 }386387 pub fn transfer(388 collection: &NonfungibleHandle<T>,389 from: &T::CrossAccountId,390 to: &T::CrossAccountId,391 token: TokenId,392 nesting_budget: &dyn Budget,393 ) -> DispatchResult {394 ensure!(395 collection.limits.transfers_enabled(),396 <CommonError<T>>::TransferNotAllowed397 );398399 let token_data =400 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;401 // TODO: require sender to be token, owner, require admins to go through transfer_from402 ensure!(403 &token_data.owner == from404 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),405 <CommonError<T>>::NoPermission406 );407408 if collection.access == AccessMode::AllowList {409 collection.check_allowlist(from)?;410 collection.check_allowlist(to)?;411 }412 <PalletCommon<T>>::ensure_correct_receiver(to)?;413414 let balance_from = <AccountBalance<T>>::get((collection.id, from))415 .checked_sub(1)416 .ok_or(<CommonError<T>>::TokenValueTooLow)?;417 let balance_to = if from != to {418 let balance_to = <AccountBalance<T>>::get((collection.id, to))419 .checked_add(1)420 .ok_or(ArithmeticError::Overflow)?;421422 ensure!(423 balance_to < collection.limits.account_token_ownership_limit(),424 <CommonError<T>>::AccountTokenLimitExceeded,425 );426427 Some(balance_to)428 } else {429 None430 };431432 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {433 let handle = <CollectionHandle<T>>::try_get(target.0)?;434 let dispatch = T::CollectionDispatch::dispatch(handle);435 let dispatch = dispatch.as_dyn();436437 dispatch.check_nesting(438 from.clone(),439 (collection.id, token),440 target.1,441 nesting_budget,442 )?;443 }444445 // =========446447 <TokenData<T>>::insert(448 (collection.id, token),449 ItemData {450 owner: to.clone(),451 ..token_data452 },453 );454455 if let Some(balance_to) = balance_to {456 // from != to457 if balance_from == 0 {458 <AccountBalance<T>>::remove((collection.id, from));459 } else {460 <AccountBalance<T>>::insert((collection.id, from), balance_from);461 }462 <AccountBalance<T>>::insert((collection.id, to), balance_to);463 <Owned<T>>::remove((collection.id, from, token));464 <Owned<T>>::insert((collection.id, to, token), true);465 }466 Self::set_allowance_unchecked(collection, from, token, None, true);467468 collection.log_mirrored(ERC721Events::Transfer {469 from: *from.as_eth(),470 to: *to.as_eth(),471 token_id: token.into(),472 });473 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(474 collection.id,475 token,476 from.clone(),477 to.clone(),478 1,479 ));480 Ok(())481 }482483 pub fn create_multiple_items(484 collection: &NonfungibleHandle<T>,485 sender: &T::CrossAccountId,486 data: Vec<CreateItemData<T>>,487 nesting_budget: &dyn Budget,488 ) -> DispatchResult {489 if !collection.is_owner_or_admin(sender) {490 ensure!(491 collection.mint_mode,492 <CommonError<T>>::PublicMintingNotAllowed493 );494 collection.check_allowlist(sender)?;495496 for item in data.iter() {497 collection.check_allowlist(&item.owner)?;498 }499 }500501 for data in data.iter() {502 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;503 }504505 let first_token = <TokensMinted<T>>::get(collection.id);506 let tokens_minted = first_token507 .checked_add(data.len() as u32)508 .ok_or(ArithmeticError::Overflow)?;509 ensure!(510 tokens_minted <= collection.limits.token_limit(),511 <CommonError<T>>::CollectionTokenLimitExceeded512 );513514 let mut balances = BTreeMap::new();515 for data in &data {516 let balance = balances517 .entry(&data.owner)518 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));519 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;520521 ensure!(522 *balance <= collection.limits.account_token_ownership_limit(),523 <CommonError<T>>::AccountTokenLimitExceeded,524 );525 }526527 for (i, data) in data.iter().enumerate() {528 let token = TokenId(first_token + i as u32 + 1);529 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {530 let handle = <CollectionHandle<T>>::try_get(target.0)?;531 let dispatch = T::CollectionDispatch::dispatch(handle);532 let dispatch = dispatch.as_dyn();533 dispatch.check_nesting(534 sender.clone(),535 (collection.id, token),536 target.1,537 nesting_budget,538 )?;539 }540 }541542 // =========543544 <TokensMinted<T>>::insert(collection.id, tokens_minted);545 for (account, balance) in balances {546 <AccountBalance<T>>::insert((collection.id, account), balance);547 }548 for (i, data) in data.into_iter().enumerate() {549 let token = first_token + i as u32 + 1;550551 <TokenData<T>>::insert(552 (collection.id, token),553 ItemData {554 const_data: data.const_data,555 variable_data: data.variable_data,556 owner: data.owner.clone(),557 },558 );559 <Owned<T>>::insert((collection.id, &data.owner, token), true);560561 collection.log_mirrored(ERC721Events::Transfer {562 from: H160::default(),563 to: *data.owner.as_eth(),564 token_id: token.into(),565 });566 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(567 collection.id,568 TokenId(token),569 data.owner.clone(),570 1,571 ));572 }573 Ok(())574 }575576 pub fn set_allowance_unchecked(577 collection: &NonfungibleHandle<T>,578 sender: &T::CrossAccountId,579 token: TokenId,580 spender: Option<&T::CrossAccountId>,581 assume_implicit_eth: bool,582 ) {583 if let Some(spender) = spender {584 let old_spender = <Allowance<T>>::get((collection.id, token));585 <Allowance<T>>::insert((collection.id, token), spender);586 // In ERC721 there is only one possible approved user of token, so we set587 // approved user to spender588 collection.log_mirrored(ERC721Events::Approval {589 owner: *sender.as_eth(),590 approved: *spender.as_eth(),591 token_id: token.into(),592 });593 // In Unique chain, any token can have any amount of approved users, so we need to594 // set allowance of old owner to 0, and allowance of new owner to 1595 if old_spender.as_ref() != Some(spender) {596 if let Some(old_owner) = old_spender {597 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(598 collection.id,599 token,600 sender.clone(),601 old_owner,602 0,603 ));604 }605 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(606 collection.id,607 token,608 sender.clone(),609 spender.clone(),610 1,611 ));612 }613 } else {614 let old_spender = <Allowance<T>>::take((collection.id, token));615 if !assume_implicit_eth {616 // In ERC721 there is only one possible approved user of token, so we set617 // approved user to zero address618 collection.log_mirrored(ERC721Events::Approval {619 owner: *sender.as_eth(),620 approved: H160::default(),621 token_id: token.into(),622 });623 }624 // In Unique chain, any token can have any amount of approved users, so we need to625 // set allowance of old owner to 0626 if let Some(old_spender) = old_spender {627 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(628 collection.id,629 token,630 sender.clone(),631 old_spender,632 0,633 ));634 }635 }636 }637638 pub fn set_allowance(639 collection: &NonfungibleHandle<T>,640 sender: &T::CrossAccountId,641 token: TokenId,642 spender: Option<&T::CrossAccountId>,643 ) -> DispatchResult {644 if collection.access == AccessMode::AllowList {645 collection.check_allowlist(sender)?;646 if let Some(spender) = spender {647 collection.check_allowlist(spender)?;648 }649 }650651 if let Some(spender) = spender {652 <PalletCommon<T>>::ensure_correct_receiver(spender)?;653 }654 let token_data =655 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;656 if &token_data.owner != sender {657 ensure!(658 collection.ignores_owned_amount(sender),659 <CommonError<T>>::CantApproveMoreThanOwned660 );661 }662663 // =========664665 Self::set_allowance_unchecked(collection, sender, token, spender, false);666 Ok(())667 }668669 fn check_allowed(670 collection: &NonfungibleHandle<T>,671 spender: &T::CrossAccountId,672 from: &T::CrossAccountId,673 token: TokenId,674 nesting_budget: &dyn Budget,675 ) -> DispatchResult {676 if spender.conv_eq(from) {677 return Ok(());678 }679 if collection.access == AccessMode::AllowList {680 // `from`, `to` checked in [`transfer`]681 collection.check_allowlist(spender)?;682 }683 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {684 // TODO: should collection owner be allowed to perform this transfer?685 ensure!(686 <PalletStructure<T>>::check_indirectly_owned(687 spender.clone(),688 source.0,689 source.1,690 None,691 nesting_budget692 )?,693 <CommonError<T>>::ApprovedValueTooLow,694 );695 return Ok(());696 }697 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {698 return Ok(());699 }700 ensure!(701 collection.ignores_allowance(spender),702 <CommonError<T>>::ApprovedValueTooLow703 );704 Ok(())705 }706707 pub fn transfer_from(708 collection: &NonfungibleHandle<T>,709 spender: &T::CrossAccountId,710 from: &T::CrossAccountId,711 to: &T::CrossAccountId,712 token: TokenId,713 nesting_budget: &dyn Budget,714 ) -> DispatchResult {715 Self::check_allowed(collection, spender, from, token, nesting_budget)?;716717 // =========718719 // Allowance is reset in [`transfer`]720 Self::transfer(collection, from, to, token, nesting_budget)721 }722723 pub fn burn_from(724 collection: &NonfungibleHandle<T>,725 spender: &T::CrossAccountId,726 from: &T::CrossAccountId,727 token: TokenId,728 nesting_budget: &dyn Budget,729 ) -> DispatchResult {730 Self::check_allowed(collection, spender, from, token, nesting_budget)?;731732 // =========733734 Self::burn(collection, from, token)735 }736737 pub fn set_variable_metadata(738 collection: &NonfungibleHandle<T>,739 sender: &T::CrossAccountId,740 token: TokenId,741 data: BoundedVec<u8, CustomDataLimit>,742 ) -> DispatchResult {743 let token_data =744 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;745 collection.check_can_update_meta(sender, &token_data.owner)?;746747 // =========748749 <TokenData<T>>::insert(750 (collection.id, token),751 ItemData {752 variable_data: data,753 ..token_data754 },755 );756 Ok(())757 }758759 pub fn check_nesting(760 handle: &NonfungibleHandle<T>,761 sender: T::CrossAccountId,762 from: (CollectionId, TokenId),763 under: TokenId,764 nesting_budget: &dyn Budget,765 ) -> DispatchResult {766 fn ensure_sender_allowed<T: Config>(767 collection: CollectionId,768 token: TokenId,769 for_nest: (CollectionId, TokenId),770 sender: T::CrossAccountId,771 budget: &dyn Budget,772 ) -> DispatchResult {773 ensure!(774 <PalletStructure<T>>::check_indirectly_owned(775 sender,776 collection,777 token,778 Some(for_nest),779 budget780 )?,781 <CommonError<T>>::OnlyOwnerAllowedToNest,782 );783 Ok(())784 }785 match handle.limits.nesting_rule() {786 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),787 NestingRule::Owner => {788 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?789 }790 NestingRule::OwnerRestricted(whitelist) => {791 ensure!(792 whitelist.contains(&from.0),793 <CommonError<T>>::SourceCollectionIsNotAllowedToNest794 );795 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?796 }797 }798 Ok(())799 }800801 /// Delegated to `create_multiple_items`802 pub fn create_item(803 collection: &NonfungibleHandle<T>,804 sender: &T::CrossAccountId,805 data: CreateItemData<T>,806 nesting_budget: &dyn Budget,807 ) -> DispatchResult {808 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)809 }810}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,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 = up_data_structs::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 collection.log_mirrored(ERC721Events::Transfer {575 from: H160::default(),576 to: *data.owner.as_eth(),577 token_id: token.into(),578 });579 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(580 collection.id,581 TokenId(token),582 data.owner.clone(),583 1,584 ));585 }586 Ok(())587 }588589 pub fn set_allowance_unchecked(590 collection: &NonfungibleHandle<T>,591 sender: &T::CrossAccountId,592 token: TokenId,593 spender: Option<&T::CrossAccountId>,594 assume_implicit_eth: bool,595 ) {596 if let Some(spender) = spender {597 let old_spender = <Allowance<T>>::get((collection.id, token));598 <Allowance<T>>::insert((collection.id, token), spender);599 // In ERC721 there is only one possible approved user of token, so we set600 // approved user to spender601 collection.log_mirrored(ERC721Events::Approval {602 owner: *sender.as_eth(),603 approved: *spender.as_eth(),604 token_id: token.into(),605 });606 // In Unique chain, any token can have any amount of approved users, so we need to607 // set allowance of old owner to 0, and allowance of new owner to 1608 if old_spender.as_ref() != Some(spender) {609 if let Some(old_owner) = old_spender {610 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(611 collection.id,612 token,613 sender.clone(),614 old_owner,615 0,616 ));617 }618 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(619 collection.id,620 token,621 sender.clone(),622 spender.clone(),623 1,624 ));625 }626 } else {627 let old_spender = <Allowance<T>>::take((collection.id, token));628 if !assume_implicit_eth {629 // In ERC721 there is only one possible approved user of token, so we set630 // approved user to zero address631 collection.log_mirrored(ERC721Events::Approval {632 owner: *sender.as_eth(),633 approved: H160::default(),634 token_id: token.into(),635 });636 }637 // In Unique chain, any token can have any amount of approved users, so we need to638 // set allowance of old owner to 0639 if let Some(old_spender) = old_spender {640 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(641 collection.id,642 token,643 sender.clone(),644 old_spender,645 0,646 ));647 }648 }649 }650651 pub fn set_allowance(652 collection: &NonfungibleHandle<T>,653 sender: &T::CrossAccountId,654 token: TokenId,655 spender: Option<&T::CrossAccountId>,656 ) -> DispatchResult {657 if collection.access == AccessMode::AllowList {658 collection.check_allowlist(sender)?;659 if let Some(spender) = spender {660 collection.check_allowlist(spender)?;661 }662 }663664 if let Some(spender) = spender {665 <PalletCommon<T>>::ensure_correct_receiver(spender)?;666 }667 let token_data =668 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;669 if &token_data.owner != sender {670 ensure!(671 collection.ignores_owned_amount(sender),672 <CommonError<T>>::CantApproveMoreThanOwned673 );674 }675676 // =========677678 Self::set_allowance_unchecked(collection, sender, token, spender, false);679 Ok(())680 }681682 fn check_allowed(683 collection: &NonfungibleHandle<T>,684 spender: &T::CrossAccountId,685 from: &T::CrossAccountId,686 token: TokenId,687 nesting_budget: &dyn Budget,688 ) -> DispatchResult {689 if spender.conv_eq(from) {690 return Ok(());691 }692 if collection.access == AccessMode::AllowList {693 // `from`, `to` checked in [`transfer`]694 collection.check_allowlist(spender)?;695 }696 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {697 // TODO: should collection owner be allowed to perform this transfer?698 ensure!(699 <PalletStructure<T>>::check_indirectly_owned(700 spender.clone(),701 source.0,702 source.1,703 None,704 nesting_budget705 )?,706 <CommonError<T>>::ApprovedValueTooLow,707 );708 return Ok(());709 }710 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {711 return Ok(());712 }713 ensure!(714 collection.ignores_allowance(spender),715 <CommonError<T>>::ApprovedValueTooLow716 );717 Ok(())718 }719720 pub fn transfer_from(721 collection: &NonfungibleHandle<T>,722 spender: &T::CrossAccountId,723 from: &T::CrossAccountId,724 to: &T::CrossAccountId,725 token: TokenId,726 nesting_budget: &dyn Budget,727 ) -> DispatchResult {728 Self::check_allowed(collection, spender, from, token, nesting_budget)?;729730 // =========731732 // Allowance is reset in [`transfer`]733 Self::transfer(collection, from, to, token, nesting_budget)734 }735736 pub fn burn_from(737 collection: &NonfungibleHandle<T>,738 spender: &T::CrossAccountId,739 from: &T::CrossAccountId,740 token: TokenId,741 nesting_budget: &dyn Budget,742 ) -> DispatchResult {743 Self::check_allowed(collection, spender, from, token, nesting_budget)?;744745 // =========746747 Self::burn(collection, from, token)748 }749750 pub fn set_variable_metadata(751 collection: &NonfungibleHandle<T>,752 sender: &T::CrossAccountId,753 token: TokenId,754 data: BoundedVec<u8, CustomDataLimit>,755 ) -> DispatchResult {756 let token_data =757 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;758 collection.check_can_update_meta(sender, &token_data.owner)?;759760 // =========761762 <TokenData<T>>::insert(763 (collection.id, token),764 ItemData {765 variable_data: data,766 ..token_data767 },768 );769 Ok(())770 }771772 pub fn check_nesting(773 handle: &NonfungibleHandle<T>,774 sender: T::CrossAccountId,775 from: (CollectionId, TokenId),776 under: TokenId,777 nesting_budget: &dyn Budget,778 ) -> DispatchResult {779 fn ensure_sender_allowed<T: Config>(780 collection: CollectionId,781 token: TokenId,782 for_nest: (CollectionId, TokenId),783 sender: T::CrossAccountId,784 budget: &dyn Budget,785 ) -> DispatchResult {786 ensure!(787 <PalletStructure<T>>::check_indirectly_owned(788 sender,789 collection,790 token,791 Some(for_nest),792 budget793 )?,794 <CommonError<T>>::OnlyOwnerAllowedToNest,795 );796 Ok(())797 }798 match handle.limits.nesting_rule() {799 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),800 NestingRule::Owner => {801 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?802 }803 NestingRule::OwnerRestricted(whitelist) => {804 ensure!(805 whitelist.contains(&from.0),806 <CommonError<T>>::SourceCollectionIsNotAllowedToNest807 );808 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?809 }810 }811 Ok(())812 }813814 /// Delegated to `create_multiple_items`815 pub fn create_item(816 collection: &NonfungibleHandle<T>,817 sender: &T::CrossAccountId,818 data: CreateItemData<T>,819 nesting_budget: &dyn Budget,820 ) -> DispatchResult {821 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)822 }823}primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -635,13 +635,20 @@
#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-pub enum PropertyPermission {
- None,
- AdminConst,
- Admin,
- ItemOwnerConst,
- ItemOwner,
- ItemOwnerOrAdmin,
+pub struct PropertyPermission {
+ pub mutable: bool,
+ pub collection_admin: bool,
+ pub token_owner: bool,
+}
+
+impl PropertyPermission {
+ pub fn none() -> Self {
+ Self {
+ mutable: true,
+ collection_admin: false,
+ token_owner: false,
+ }
+ }
}
#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]