12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091#![cfg_attr(not(feature = "std"), no_std)]9293use erc::ERC721Events;94use evm_coder::ToLog;95use frame_support::{96 BoundedVec, ensure, fail, transactional,97 storage::with_transaction,98 pallet_prelude::DispatchResultWithPostInfo,99 pallet_prelude::Weight,100 dispatch::{PostDispatchInfo, Pays},101};102use up_data_structs::{103 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,104 mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey, PropertyValue,105 PropertyKeyPermission, PropertyScope, TrySetProperty, TokenChild, AuxPropertyValue,106 PropertiesPermissionMap, TokenProperties as TokenPropertiesT,107};108use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};109use pallet_common::{110 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,111 eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,112 weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info, SetPropertyMode,113};114use pallet_structure::{Pallet as PalletStructure, Error as StructureError};115use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};116use sp_core::{Get, H160};117use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};118use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};119use core::ops::Deref;120use codec::{Encode, Decode, MaxEncodedLen};121use scale_info::TypeInfo;122123pub use pallet::*;124use weights::WeightInfo;125#[cfg(feature = "runtime-benchmarks")]126pub mod benchmarking;127pub mod common;128pub mod erc;129pub mod weights;130131pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::Config>::CrossAccountId>;132pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;133134135136#[struct_versioning::versioned(version = 2, upper)]137#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]138pub struct ItemData<CrossAccountId> {139 #[version(..2)]140 pub const_data: BoundedVec<u8, CustomDataLimit>,141142 #[version(..2)]143 pub variable_data: BoundedVec<u8, CustomDataLimit>,144145 pub owner: CrossAccountId,146}147148#[frame_support::pallet]149pub mod pallet {150 use super::*;151 use frame_support::{152 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,153 };154 use up_data_structs::{CollectionId, TokenId};155 use super::weights::WeightInfo;156157 #[pallet::error]158 pub enum Error<T> {159 160 NotNonfungibleDataUsedToMintFungibleCollectionToken,161 162 NonfungibleItemsHaveNoAmount,163 164 CantBurnNftWithChildren,165 }166167 #[pallet::config]168 pub trait Config:169 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config170 {171 type WeightInfo: WeightInfo;172 }173174 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);175176 #[pallet::pallet]177 #[pallet::storage_version(STORAGE_VERSION)]178 pub struct Pallet<T>(_);179180 181 #[pallet::storage]182 pub type TokensMinted<T: Config> =183 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;184185 186 #[pallet::storage]187 pub type TokensBurnt<T: Config> =188 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;189190 191 #[pallet::storage]192 pub type TokenData<T: Config> = StorageNMap<193 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),194 Value = ItemData<T::CrossAccountId>,195 QueryKind = OptionQuery,196 >;197198 199 #[pallet::storage]200 #[pallet::getter(fn token_properties)]201 pub type TokenProperties<T: Config> = StorageNMap<202 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),203 Value = TokenPropertiesT,204 QueryKind = ValueQuery,205 >;206207 208 209 210 211 212 213 214 215 216 #[pallet::storage]217 #[pallet::getter(fn token_aux_property)]218 pub type TokenAuxProperties<T: Config> = StorageNMap<219 Key = (220 Key<Twox64Concat, CollectionId>,221 Key<Twox64Concat, TokenId>,222 Key<Twox64Concat, PropertyScope>,223 Key<Twox64Concat, PropertyKey>,224 ),225 Value = AuxPropertyValue,226 QueryKind = OptionQuery,227 >;228229 230 #[pallet::storage]231 pub type Owned<T: Config> = StorageNMap<232 Key = (233 Key<Twox64Concat, CollectionId>,234 Key<Blake2_128Concat, T::CrossAccountId>,235 Key<Twox64Concat, TokenId>,236 ),237 Value = bool,238 QueryKind = ValueQuery,239 >;240241 242 #[pallet::storage]243 #[pallet::getter(fn token_children)]244 pub type TokenChildren<T: Config> = StorageNMap<245 Key = (246 Key<Twox64Concat, CollectionId>,247 Key<Twox64Concat, TokenId>,248 Key<Twox64Concat, (CollectionId, TokenId)>,249 ),250 Value = bool,251 QueryKind = ValueQuery,252 >;253254 255 #[pallet::storage]256 pub type AccountBalance<T: Config> = StorageNMap<257 Key = (258 Key<Twox64Concat, CollectionId>,259 Key<Blake2_128Concat, T::CrossAccountId>,260 ),261 Value = u32,262 QueryKind = ValueQuery,263 >;264265 266 #[pallet::storage]267 pub type Allowance<T: Config> = StorageNMap<268 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),269 Value = T::CrossAccountId,270 QueryKind = OptionQuery,271 >;272273 274 #[pallet::storage]275 pub type CollectionAllowance<T: Config> = StorageNMap<276 Key = (277 Key<Twox64Concat, CollectionId>,278 Key<Blake2_128Concat, T::CrossAccountId>,279 Key<Blake2_128Concat, T::CrossAccountId>,280 ),281 Value = bool,282 QueryKind = ValueQuery,283 >;284285 #[pallet::genesis_config]286 pub struct GenesisConfig<T>(PhantomData<T>);287288 #[cfg(feature = "std")]289 impl<T: Config> Default for GenesisConfig<T> {290 fn default() -> Self {291 Self(Default::default())292 }293 }294295 #[pallet::genesis_build]296 impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {297 fn build(&self) {298 StorageVersion::new(1).put::<Pallet<T>>();299 }300 }301}302303pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);304impl<T: Config> NonfungibleHandle<T> {305 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {306 Self(inner)307 }308 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {309 self.0310 }311 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {312 &mut self.0313 }314}315316impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {317 fn recorder(&self) -> &SubstrateRecorder<T> {318 self.0.recorder()319 }320 fn into_recorder(self) -> SubstrateRecorder<T> {321 self.0.into_recorder()322 }323}324impl<T: Config> Deref for NonfungibleHandle<T> {325 type Target = pallet_common::CollectionHandle<T>;326327 fn deref(&self) -> &Self::Target {328 &self.0329 }330}331332impl<T: Config> Pallet<T> {333 334 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {335 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)336 }337338 339 340 341 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {342 <TokenData<T>>::contains_key((collection.id, token))343 }344345 346 347 348 pub fn set_scoped_token_property(349 collection_id: CollectionId,350 token_id: TokenId,351 scope: PropertyScope,352 property: Property,353 ) -> DispatchResult {354 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {355 properties.try_scoped_set(scope, property.key, property.value)356 })357 .map_err(<CommonError<T>>::from)?;358359 Ok(())360 }361362 363 pub fn set_scoped_token_properties(364 collection_id: CollectionId,365 token_id: TokenId,366 scope: PropertyScope,367 properties: impl Iterator<Item = Property>,368 ) -> DispatchResult {369 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {370 stored_properties.try_scoped_set_from_iter(scope, properties)371 })372 .map_err(<CommonError<T>>::from)?;373374 Ok(())375 }376377 378 379 380 pub fn try_mutate_token_aux_property<R, E>(381 collection_id: CollectionId,382 token_id: TokenId,383 scope: PropertyScope,384 key: PropertyKey,385 f: impl FnOnce(&mut Option<AuxPropertyValue>) -> Result<R, E>,386 ) -> Result<R, E> {387 <TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)388 }389390 391 pub fn remove_token_aux_property(392 collection_id: CollectionId,393 token_id: TokenId,394 scope: PropertyScope,395 key: PropertyKey,396 ) {397 <TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));398 }399400 401 402 403 pub fn iterate_token_aux_properties(404 collection_id: CollectionId,405 token_id: TokenId,406 scope: PropertyScope,407 ) -> impl Iterator<Item = (PropertyKey, AuxPropertyValue)> {408 <TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))409 }410411 412 pub fn current_token_id(collection_id: CollectionId) -> TokenId {413 TokenId(<TokensMinted<T>>::get(collection_id))414 }415}416417418impl<T: Config> Pallet<T> {419 420 421 422 423 424 pub fn init_collection(425 owner: T::CrossAccountId,426 payer: T::CrossAccountId,427 data: CreateCollectionData<T::CrossAccountId>,428 ) -> Result<CollectionId, DispatchError> {429 <PalletCommon<T>>::init_collection(owner, payer, data)430 }431432 433 434 435 436 pub fn destroy_collection(437 collection: NonfungibleHandle<T>,438 sender: &T::CrossAccountId,439 ) -> DispatchResult {440 let id = collection.id;441442 if Self::collection_has_tokens(id) {443 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());444 }445446 447448 PalletCommon::destroy_collection(collection.0, sender)?;449450 let _ = <TokenData<T>>::clear_prefix((id,), u32::MAX, None);451 let _ = <TokenChildren<T>>::clear_prefix((id,), u32::MAX, None);452 let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);453 <TokensMinted<T>>::remove(id);454 <TokensBurnt<T>>::remove(id);455 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);456 let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);457 let _ = <CollectionAllowance<T>>::clear_prefix((id,), u32::MAX, None);458 Ok(())459 }460461 462 463 464 465 466 467 468 469 470 pub fn burn(471 collection: &NonfungibleHandle<T>,472 sender: &T::CrossAccountId,473 token: TokenId,474 ) -> DispatchResult {475 let token_data =476 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;477 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);478479 if collection.permissions.access() == AccessMode::AllowList {480 collection.check_allowlist(sender)?;481 }482483 if Self::token_has_children(collection.id, token) {484 return Err(<Error<T>>::CantBurnNftWithChildren.into());485 }486487 let burnt = <TokensBurnt<T>>::get(collection.id)488 .checked_add(1)489 .ok_or(ArithmeticError::Overflow)?;490491 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))492 .checked_sub(1)493 .ok_or(ArithmeticError::Overflow)?;494495 496497 if balance == 0 {498 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));499 } else {500 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);501 }502503 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);504505 <Owned<T>>::remove((collection.id, &token_data.owner, token));506 <TokensBurnt<T>>::insert(collection.id, burnt);507 <TokenData<T>>::remove((collection.id, token));508 <TokenProperties<T>>::remove((collection.id, token));509 let _ = <TokenAuxProperties<T>>::clear_prefix((collection.id, token), u32::MAX, None);510 let old_spender = <Allowance<T>>::take((collection.id, token));511512 if let Some(old_spender) = old_spender {513 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(514 collection.id,515 token,516 token_data.owner.clone(),517 old_spender,518 0,519 ));520 }521522 <PalletEvm<T>>::deposit_log(523 ERC721Events::Transfer {524 from: *token_data.owner.as_eth(),525 to: H160::default(),526 token_id: token.into(),527 }528 .to_log(collection_id_to_address(collection.id)),529 );530 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(531 collection.id,532 token,533 token_data.owner,534 1,535 ));536 Ok(())537 }538539 540 541 542 543 544 545 #[transactional]546 pub fn burn_recursively(547 collection: &NonfungibleHandle<T>,548 sender: &T::CrossAccountId,549 token: TokenId,550 self_budget: &dyn Budget,551 breadth_budget: &dyn Budget,552 ) -> DispatchResultWithPostInfo {553 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);554555 let current_token_account =556 T::CrossTokenAddressMapping::token_to_address(collection.id, token);557558 let mut weight = Weight::zero();559560 561 562 for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {563 ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);564 let PostDispatchInfo { actual_weight, .. } =565 <PalletStructure<T>>::burn_item_recursively(566 current_token_account.clone(),567 collection,568 token,569 self_budget,570 breadth_budget,571 )?;572 if let Some(actual_weight) = actual_weight {573 weight = weight.saturating_add(actual_weight);574 }575 }576577 Self::burn(collection, sender, token)?;578 DispatchResultWithPostInfo::Ok(PostDispatchInfo {579 actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),580 pays_fee: Pays::Yes,581 })582 }583584 585 586 587 588 589 590 591 592 593 594 595 #[transactional]596 fn modify_token_properties(597 collection: &NonfungibleHandle<T>,598 sender: &T::CrossAccountId,599 token_id: TokenId,600 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,601 mode: SetPropertyMode,602 nesting_budget: &dyn Budget,603 ) -> DispatchResult {604 let mut is_token_owner = pallet_common::LazyValue::new(|| {605 if let SetPropertyMode::NewToken {606 mint_target_is_sender,607 } = mode608 {609 return Ok(mint_target_is_sender);610 }611612 let is_owned = <PalletStructure<T>>::check_indirectly_owned(613 sender.clone(),614 collection.id,615 token_id,616 None,617 nesting_budget,618 )?;619620 Ok(is_owned)621 });622623 let is_new_token = matches!(mode, SetPropertyMode::NewToken { .. });624625 let mut is_token_exist = pallet_common::LazyValue::new(|| {626 if is_new_token {627 debug_assert!(Self::token_exists(collection, token_id));628 true629 } else {630 Self::token_exists(collection, token_id)631 }632 });633634 let stored_properties = if is_new_token {635 TokenPropertiesT::new()636 } else {637 <TokenProperties<T>>::get((collection.id, token_id))638 };639640 <PalletCommon<T>>::modify_token_properties(641 collection,642 sender,643 token_id,644 &mut is_token_exist,645 properties_updates,646 stored_properties,647 &mut is_token_owner,648 |properties| <TokenProperties<T>>::set((collection.id, token_id), properties),649 erc::ERC721TokenEvent::TokenChanged {650 token_id: token_id.into(),651 }652 .to_log(T::ContractAddress::get()),653 )654 }655656 pub fn next_token_id(collection: &NonfungibleHandle<T>) -> Result<TokenId, DispatchError> {657 let next_token_id = <TokensMinted<T>>::get(collection.id)658 .checked_add(1)659 .ok_or(<CommonError<T>>::CollectionTokenLimitExceeded)?;660661 ensure!(662 collection.limits.token_limit() >= next_token_id,663 <CommonError<T>>::CollectionTokenLimitExceeded664 );665666 Ok(TokenId(next_token_id))667 }668669 670 671 672 673 674 pub fn set_token_properties(675 collection: &NonfungibleHandle<T>,676 sender: &T::CrossAccountId,677 token_id: TokenId,678 properties: impl Iterator<Item = Property>,679 mode: SetPropertyMode,680 nesting_budget: &dyn Budget,681 ) -> DispatchResult {682 Self::modify_token_properties(683 collection,684 sender,685 token_id,686 properties.map(|p| (p.key, Some(p.value))),687 mode,688 nesting_budget,689 )690 }691692 693 694 695 696 697 pub fn set_token_property(698 collection: &NonfungibleHandle<T>,699 sender: &T::CrossAccountId,700 token_id: TokenId,701 property: Property,702 nesting_budget: &dyn Budget,703 ) -> DispatchResult {704 Self::set_token_properties(705 collection,706 sender,707 token_id,708 [property].into_iter(),709 SetPropertyMode::ExistingToken,710 nesting_budget,711 )712 }713714 715 716 717 718 719 pub fn delete_token_properties(720 collection: &NonfungibleHandle<T>,721 sender: &T::CrossAccountId,722 token_id: TokenId,723 property_keys: impl Iterator<Item = PropertyKey>,724 nesting_budget: &dyn Budget,725 ) -> DispatchResult {726 Self::modify_token_properties(727 collection,728 sender,729 token_id,730 property_keys.into_iter().map(|key| (key, None)),731 SetPropertyMode::ExistingToken,732 nesting_budget,733 )734 }735736 737 738 739 740 741 pub fn delete_token_property(742 collection: &NonfungibleHandle<T>,743 sender: &T::CrossAccountId,744 token_id: TokenId,745 property_key: PropertyKey,746 nesting_budget: &dyn Budget,747 ) -> DispatchResult {748 Self::delete_token_properties(749 collection,750 sender,751 token_id,752 [property_key].into_iter(),753 nesting_budget,754 )755 }756757 758 pub fn set_collection_properties(759 collection: &NonfungibleHandle<T>,760 sender: &T::CrossAccountId,761 properties: Vec<Property>,762 ) -> DispatchResult {763 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())764 }765766 767 pub fn delete_collection_properties(768 collection: &CollectionHandle<T>,769 sender: &T::CrossAccountId,770 property_keys: Vec<PropertyKey>,771 ) -> DispatchResult {772 <PalletCommon<T>>::delete_collection_properties(773 collection,774 sender,775 property_keys.into_iter(),776 )777 }778779 780 781 782 pub fn set_token_property_permissions(783 collection: &CollectionHandle<T>,784 sender: &T::CrossAccountId,785 property_permissions: Vec<PropertyKeyPermission>,786 ) -> DispatchResult {787 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)788 }789790 791 792 793 pub fn set_scoped_token_property_permissions(794 collection: &CollectionHandle<T>,795 sender: &T::CrossAccountId,796 scope: PropertyScope,797 property_permissions: Vec<PropertyKeyPermission>,798 ) -> DispatchResult {799 <PalletCommon<T>>::set_scoped_token_property_permissions(800 collection,801 sender,802 scope,803 property_permissions,804 )805 }806807 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {808 <PalletCommon<T>>::property_permissions(collection_id)809 }810811 pub fn check_token_immediate_ownership(812 collection: &NonfungibleHandle<T>,813 token: TokenId,814 possible_owner: &T::CrossAccountId,815 ) -> DispatchResult {816 let token_data =817 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;818 ensure!(819 &token_data.owner == possible_owner,820 <CommonError<T>>::NoPermission821 );822 Ok(())823 }824825 826 827 828 829 830 831 832 833 834 pub fn transfer(835 collection: &NonfungibleHandle<T>,836 from: &T::CrossAccountId,837 to: &T::CrossAccountId,838 token: TokenId,839 nesting_budget: &dyn Budget,840 ) -> DispatchResultWithPostInfo {841 ensure!(842 collection.limits.transfers_enabled(),843 <CommonError<T>>::TransferNotAllowed844 );845846 let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();847 let token_data =848 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;849 ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);850851 if collection.permissions.access() == AccessMode::AllowList {852 collection.check_allowlist(from)?;853 collection.check_allowlist(to)?;854 actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;855 }856 <PalletCommon<T>>::ensure_correct_receiver(to)?;857858 let balance_from = <AccountBalance<T>>::get((collection.id, from))859 .checked_sub(1)860 .ok_or(<CommonError<T>>::TokenValueTooLow)?;861 let balance_to = if from != to {862 let balance_to = <AccountBalance<T>>::get((collection.id, to))863 .checked_add(1)864 .ok_or(ArithmeticError::Overflow)?;865866 ensure!(867 balance_to < collection.limits.account_token_ownership_limit(),868 <CommonError<T>>::AccountTokenLimitExceeded,869 );870871 Some(balance_to)872 } else {873 None874 };875876 <PalletStructure<T>>::nest_if_sent_to_token(877 from.clone(),878 to,879 collection.id,880 token,881 nesting_budget,882 )?;883884 885886 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);887888 <TokenData<T>>::insert((collection.id, token), ItemData { owner: to.clone() });889890 if let Some(balance_to) = balance_to {891 892 if balance_from == 0 {893 <AccountBalance<T>>::remove((collection.id, from));894 } else {895 <AccountBalance<T>>::insert((collection.id, from), balance_from);896 }897 <AccountBalance<T>>::insert((collection.id, to), balance_to);898 <Owned<T>>::remove((collection.id, from, token));899 <Owned<T>>::insert((collection.id, to, token), true);900 }901 Self::set_allowance_unchecked(collection, from, token, None, true);902903 <PalletEvm<T>>::deposit_log(904 ERC721Events::Transfer {905 from: *from.as_eth(),906 to: *to.as_eth(),907 token_id: token.into(),908 }909 .to_log(collection_id_to_address(collection.id)),910 );911 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(912 collection.id,913 token,914 from.clone(),915 to.clone(),916 1,917 ));918919 Ok(PostDispatchInfo {920 actual_weight: Some(actual_weight),921 pays_fee: Pays::Yes,922 })923 }924925 926 927 928 929 930 931 932 933 934 935 pub fn create_multiple_items(936 collection: &NonfungibleHandle<T>,937 sender: &T::CrossAccountId,938 data: Vec<CreateItemData<T>>,939 nesting_budget: &dyn Budget,940 ) -> DispatchResult {941 if !collection.is_owner_or_admin(sender) {942 ensure!(943 collection.permissions.mint_mode(),944 <CommonError<T>>::PublicMintingNotAllowed945 );946 collection.check_allowlist(sender)?;947948 for item in data.iter() {949 collection.check_allowlist(&item.owner)?;950 }951 }952953 for data in data.iter() {954 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;955 }956957 let first_token = <TokensMinted<T>>::get(collection.id);958 let tokens_minted = first_token959 .checked_add(data.len() as u32)960 .ok_or(ArithmeticError::Overflow)?;961 ensure!(962 tokens_minted <= collection.limits.token_limit(),963 <CommonError<T>>::CollectionTokenLimitExceeded964 );965966 let mut balances = BTreeMap::new();967 for data in &data {968 let balance = balances969 .entry(&data.owner)970 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));971 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;972973 ensure!(974 *balance <= collection.limits.account_token_ownership_limit(),975 <CommonError<T>>::AccountTokenLimitExceeded,976 );977 }978979 for (i, data) in data.iter().enumerate() {980 let token = TokenId(first_token + i as u32 + 1);981982 <PalletStructure<T>>::check_nesting(983 sender.clone(),984 &data.owner,985 collection.id,986 token,987 nesting_budget,988 )?;989 }990991 992993 with_transaction(|| {994 for (i, data) in data.iter().enumerate() {995 let token = first_token + i as u32 + 1;996997 <TokenData<T>>::insert(998 (collection.id, token),999 ItemData {1000 1001 owner: data.owner.clone(),1002 },1003 );10041005 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(1006 &data.owner,1007 collection.id,1008 TokenId(token),1009 );10101011 if let Err(e) = Self::set_token_properties(1012 collection,1013 sender,1014 TokenId(token),1015 data.properties.clone().into_iter(),1016 SetPropertyMode::NewToken {1017 mint_target_is_sender: sender.conv_eq(&data.owner),1018 },1019 nesting_budget,1020 ) {1021 return TransactionOutcome::Rollback(Err(e));1022 }1023 }1024 TransactionOutcome::Commit(Ok(()))1025 })?;10261027 <TokensMinted<T>>::insert(collection.id, tokens_minted);1028 for (account, balance) in balances {1029 <AccountBalance<T>>::insert((collection.id, account), balance);1030 }1031 for (i, data) in data.into_iter().enumerate() {1032 let token = first_token + i as u32 + 1;1033 <Owned<T>>::insert((collection.id, &data.owner, token), true);10341035 <PalletEvm<T>>::deposit_log(1036 ERC721Events::Transfer {1037 from: H160::default(),1038 to: *data.owner.as_eth(),1039 token_id: token.into(),1040 }1041 .to_log(collection_id_to_address(collection.id)),1042 );1043 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1044 collection.id,1045 TokenId(token),1046 data.owner.clone(),1047 1,1048 ));1049 }1050 Ok(())1051 }10521053 pub fn set_allowance_unchecked(1054 collection: &NonfungibleHandle<T>,1055 sender: &T::CrossAccountId,1056 token: TokenId,1057 spender: Option<&T::CrossAccountId>,1058 assume_implicit_eth: bool,1059 ) {1060 if let Some(spender) = spender {1061 let old_spender = <Allowance<T>>::get((collection.id, token));1062 <Allowance<T>>::insert((collection.id, token), spender);1063 1064 1065 <PalletEvm<T>>::deposit_log(1066 ERC721Events::Approval {1067 owner: *sender.as_eth(),1068 approved: *spender.as_eth(),1069 token_id: token.into(),1070 }1071 .to_log(collection_id_to_address(collection.id)),1072 );1073 1074 1075 if old_spender.as_ref() != Some(spender) {1076 if let Some(old_owner) = old_spender {1077 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1078 collection.id,1079 token,1080 sender.clone(),1081 old_owner,1082 0,1083 ));1084 }1085 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1086 collection.id,1087 token,1088 sender.clone(),1089 spender.clone(),1090 1,1091 ));1092 }1093 } else {1094 let old_spender = <Allowance<T>>::take((collection.id, token));1095 if !assume_implicit_eth {1096 1097 1098 <PalletEvm<T>>::deposit_log(1099 ERC721Events::Approval {1100 owner: *sender.as_eth(),1101 approved: H160::default(),1102 token_id: token.into(),1103 }1104 .to_log(collection_id_to_address(collection.id)),1105 );1106 }1107 1108 1109 if let Some(old_spender) = old_spender {1110 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1111 collection.id,1112 token,1113 sender.clone(),1114 old_spender,1115 0,1116 ));1117 }1118 }1119 }11201121 pub fn get_allowance(1122 collection: &NonfungibleHandle<T>,1123 token_id: TokenId,1124 ) -> Result<Option<T::CrossAccountId>, DispatchError> {1125 ensure!(1126 <TokenData<T>>::get((collection.id, token_id)).is_some(),1127 <CommonError<T>>::TokenNotFound1128 );1129 Ok(<Allowance<T>>::get((collection.id, token_id)))1130 }11311132 1133 1134 1135 pub fn set_allowance(1136 collection: &NonfungibleHandle<T>,1137 sender: &T::CrossAccountId,1138 token: TokenId,1139 spender: Option<&T::CrossAccountId>,1140 ) -> DispatchResult {1141 if collection.permissions.access() == AccessMode::AllowList {1142 collection.check_allowlist(sender)?;1143 if let Some(spender) = spender {1144 collection.check_allowlist(spender)?;1145 }1146 }11471148 if let Some(spender) = spender {1149 <PalletCommon<T>>::ensure_correct_receiver(spender)?;1150 }11511152 let token_data =1153 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1154 if &token_data.owner != sender {1155 ensure!(1156 collection.ignores_owned_amount(sender),1157 <CommonError<T>>::CantApproveMoreThanOwned1158 );1159 }11601161 11621163 Self::set_allowance_unchecked(collection, sender, token, spender, false);1164 Ok(())1165 }11661167 1168 1169 1170 1171 1172 pub fn set_allowance_from(1173 collection: &NonfungibleHandle<T>,1174 sender: &T::CrossAccountId,1175 from: &T::CrossAccountId,1176 token: TokenId,1177 to: Option<&T::CrossAccountId>,1178 ) -> DispatchResult {1179 if collection.permissions.access() == AccessMode::AllowList {1180 collection.check_allowlist(sender)?;1181 collection.check_allowlist(from)?;1182 if let Some(to) = to {1183 collection.check_allowlist(to)?;1184 }1185 }11861187 if let Some(to) = to {1188 <PalletCommon<T>>::ensure_correct_receiver(to)?;1189 }11901191 ensure!(1192 sender.conv_eq(from),1193 <CommonError<T>>::AddressIsNotEthMirror1194 );11951196 let token_data =1197 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1198 if token_data.owner != *from {1199 ensure!(1200 collection.limits.owner_can_transfer()1201 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),1202 <CommonError<T>>::CantApproveMoreThanOwned1203 );1204 }12051206 12071208 Self::set_allowance_unchecked(collection, from, token, to, false);1209 Ok(())1210 }12111212 1213 fn check_allowed(1214 collection: &NonfungibleHandle<T>,1215 spender: &T::CrossAccountId,1216 from: &T::CrossAccountId,1217 token: TokenId,1218 nesting_budget: &dyn Budget,1219 ) -> DispatchResult {1220 if spender.conv_eq(from) {1221 return Ok(());1222 }1223 if collection.permissions.access() == AccessMode::AllowList {1224 1225 collection.check_allowlist(spender)?;1226 }12271228 if collection.ignores_token_restrictions(spender) {1229 return Ok(());1230 }12311232 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1233 ensure!(1234 <PalletStructure<T>>::check_indirectly_owned(1235 spender.clone(),1236 source.0,1237 source.1,1238 None,1239 nesting_budget1240 )?,1241 <CommonError<T>>::ApprovedValueTooLow,1242 );1243 return Ok(());1244 }1245 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {1246 return Ok(());1247 }1248 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1249 return Ok(());1250 }12511252 Err(<CommonError<T>>::ApprovedValueTooLow.into())1253 }12541255 1256 1257 1258 1259 1260 1261 pub fn transfer_from(1262 collection: &NonfungibleHandle<T>,1263 spender: &T::CrossAccountId,1264 from: &T::CrossAccountId,1265 to: &T::CrossAccountId,1266 token: TokenId,1267 nesting_budget: &dyn Budget,1268 ) -> DispatchResultWithPostInfo {1269 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12701271 12721273 1274 let mut result = Self::transfer(collection, from, to, token, nesting_budget);1275 add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::check_allowed_raw());1276 result1277 }12781279 1280 1281 1282 1283 1284 1285 pub fn burn_from(1286 collection: &NonfungibleHandle<T>,1287 spender: &T::CrossAccountId,1288 from: &T::CrossAccountId,1289 token: TokenId,1290 nesting_budget: &dyn Budget,1291 ) -> DispatchResult {1292 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12931294 12951296 Self::burn(collection, from, token)1297 }12981299 1300 1301 pub fn check_nesting(1302 handle: &NonfungibleHandle<T>,1303 sender: T::CrossAccountId,1304 from: (CollectionId, TokenId),1305 under: TokenId,1306 nesting_budget: &dyn Budget,1307 ) -> DispatchResult {1308 let nesting = handle.permissions.nesting();13091310 #[cfg(not(feature = "runtime-benchmarks"))]1311 let permissive = false;1312 #[cfg(feature = "runtime-benchmarks")]1313 let permissive = nesting.permissive;13141315 if permissive {1316 ensure!(1317 <TokenData<T>>::contains_key((handle.id, under)),1318 <CommonError<T>>::TokenNotFound1319 );1320 } else if nesting.token_owner1321 && <PalletStructure<T>>::check_indirectly_owned(1322 sender.clone(),1323 handle.id,1324 under,1325 Some(from),1326 nesting_budget,1327 )? {1328 1329 } else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {1330 1331 let _ = <PalletStructure<T>>::get_checked_topmost_owner(1332 handle.id,1333 under,1334 Some(from),1335 nesting_budget,1336 )?1337 .ok_or(<CommonError<T>>::TokenNotFound)?;1338 } else {1339 fail!(<CommonError<T>>::UserIsNotAllowedToNest);1340 }13411342 if let Some(whitelist) = &nesting.restricted {1343 ensure!(1344 whitelist.contains(&from.0),1345 <CommonError<T>>::SourceCollectionIsNotAllowedToNest1346 );1347 }1348 Ok(())1349 }13501351 fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {1352 if to_nest.0 != pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {1353 <TokenChildren<T>>::insert((under.0, under.1, to_nest), true);1354 }1355 }13561357 fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1358 if to_unnest.0 != pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {1359 <TokenChildren<T>>::remove((under.0, under.1, to_unnest));1360 }1361 }13621363 fn collection_has_tokens(collection_id: CollectionId) -> bool {1364 <TokenData<T>>::iter_prefix((collection_id,))1365 .next()1366 .is_some()1367 }13681369 fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1370 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1371 .next()1372 .is_some()1373 }13741375 pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1376 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1377 .map(|((child_collection_id, child_id), _)| TokenChild {1378 collection: child_collection_id,1379 token: child_id,1380 })1381 .collect()1382 }13831384 1385 1386 1387 1388 1389 pub fn create_item(1390 collection: &NonfungibleHandle<T>,1391 sender: &T::CrossAccountId,1392 data: CreateItemData<T>,1393 nesting_budget: &dyn Budget,1394 ) -> DispatchResult {1395 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1396 }13971398 1399 1400 1401 1402 1403 1404 pub fn set_allowance_for_all(1405 collection: &NonfungibleHandle<T>,1406 owner: &T::CrossAccountId,1407 operator: &T::CrossAccountId,1408 approve: bool,1409 ) -> DispatchResult {1410 <PalletCommon<T>>::set_allowance_for_all(1411 collection,1412 owner,1413 operator,1414 approve,1415 || <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve),1416 ERC721Events::ApprovalForAll {1417 owner: *owner.as_eth(),1418 operator: *operator.as_eth(),1419 approved: approve,1420 }1421 .to_log(collection_id_to_address(collection.id)),1422 )1423 }14241425 1426 pub fn allowance_for_all(1427 collection: &NonfungibleHandle<T>,1428 owner: &T::CrossAccountId,1429 operator: &T::CrossAccountId,1430 ) -> bool {1431 <CollectionAllowance<T>>::get((collection.id, owner, operator))1432 }14331434 pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {1435 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1436 properties.recompute_consumed_space();1437 });14381439 Ok(())1440 }1441}