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, CollectionFlags, CustomDataLimit, TokenId, CreateCollectionData,104 CreateNftExData, mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey,105 PropertyValue, PropertyKeyPermission, PropertyScope, TrySetProperty, TokenChild,106 AuxPropertyValue, 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,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 frame_system::pallet_prelude::*;155 use up_data_structs::{CollectionId, TokenId};156 use super::weights::WeightInfo;157158 #[pallet::error]159 pub enum Error<T> {160 161 NotNonfungibleDataUsedToMintFungibleCollectionToken,162 163 NonfungibleItemsHaveNoAmount,164 165 CantBurnNftWithChildren,166 }167168 #[pallet::config]169 pub trait Config:170 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config171 {172 type WeightInfo: WeightInfo;173 }174175 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);176177 #[pallet::pallet]178 #[pallet::storage_version(STORAGE_VERSION)]179 pub struct Pallet<T>(_);180181 182 #[pallet::storage]183 pub type TokensMinted<T: Config> =184 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;185186 187 #[pallet::storage]188 pub type TokensBurnt<T: Config> =189 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;190191 192 #[pallet::storage]193 pub type TokenData<T: Config> = StorageNMap<194 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),195 Value = ItemData<T::CrossAccountId>,196 QueryKind = OptionQuery,197 >;198199 200 #[pallet::storage]201 #[pallet::getter(fn token_properties)]202 pub type TokenProperties<T: Config> = StorageNMap<203 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),204 Value = TokenPropertiesT,205 QueryKind = ValueQuery,206 >;207208 209 210 211 212 213 214 215 216 217 #[pallet::storage]218 #[pallet::getter(fn token_aux_property)]219 pub type TokenAuxProperties<T: Config> = StorageNMap<220 Key = (221 Key<Twox64Concat, CollectionId>,222 Key<Twox64Concat, TokenId>,223 Key<Twox64Concat, PropertyScope>,224 Key<Twox64Concat, PropertyKey>,225 ),226 Value = AuxPropertyValue,227 QueryKind = OptionQuery,228 >;229230 231 #[pallet::storage]232 pub type Owned<T: Config> = StorageNMap<233 Key = (234 Key<Twox64Concat, CollectionId>,235 Key<Blake2_128Concat, T::CrossAccountId>,236 Key<Twox64Concat, TokenId>,237 ),238 Value = bool,239 QueryKind = ValueQuery,240 >;241242 243 #[pallet::storage]244 #[pallet::getter(fn token_children)]245 pub type TokenChildren<T: Config> = StorageNMap<246 Key = (247 Key<Twox64Concat, CollectionId>,248 Key<Twox64Concat, TokenId>,249 Key<Twox64Concat, (CollectionId, TokenId)>,250 ),251 Value = bool,252 QueryKind = ValueQuery,253 >;254255 256 #[pallet::storage]257 pub type AccountBalance<T: Config> = StorageNMap<258 Key = (259 Key<Twox64Concat, CollectionId>,260 Key<Blake2_128Concat, T::CrossAccountId>,261 ),262 Value = u32,263 QueryKind = ValueQuery,264 >;265266 267 #[pallet::storage]268 pub type Allowance<T: Config> = StorageNMap<269 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),270 Value = T::CrossAccountId,271 QueryKind = OptionQuery,272 >;273274 275 #[pallet::storage]276 pub type CollectionAllowance<T: Config> = StorageNMap<277 Key = (278 Key<Twox64Concat, CollectionId>,279 Key<Blake2_128Concat, T::CrossAccountId>,280 Key<Blake2_128Concat, T::CrossAccountId>,281 ),282 Value = bool,283 QueryKind = ValueQuery,284 >;285286 287 #[pallet::hooks]288 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {289 fn on_runtime_upgrade() -> Weight {290 StorageVersion::new(1).put::<Pallet<T>>();291292 Weight::zero()293 }294 }295}296297pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);298impl<T: Config> NonfungibleHandle<T> {299 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {300 Self(inner)301 }302 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {303 self.0304 }305 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {306 &mut self.0307 }308}309310impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {311 fn recorder(&self) -> &SubstrateRecorder<T> {312 self.0.recorder()313 }314 fn into_recorder(self) -> SubstrateRecorder<T> {315 self.0.into_recorder()316 }317}318impl<T: Config> Deref for NonfungibleHandle<T> {319 type Target = pallet_common::CollectionHandle<T>;320321 fn deref(&self) -> &Self::Target {322 &self.0323 }324}325326impl<T: Config> Pallet<T> {327 328 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {329 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)330 }331332 333 334 335 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {336 <TokenData<T>>::contains_key((collection.id, token))337 }338339 340 341 342 pub fn set_scoped_token_property(343 collection_id: CollectionId,344 token_id: TokenId,345 scope: PropertyScope,346 property: Property,347 ) -> DispatchResult {348 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {349 properties.try_scoped_set(scope, property.key, property.value)350 })351 .map_err(<CommonError<T>>::from)?;352353 Ok(())354 }355356 357 pub fn set_scoped_token_properties(358 collection_id: CollectionId,359 token_id: TokenId,360 scope: PropertyScope,361 properties: impl Iterator<Item = Property>,362 ) -> DispatchResult {363 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {364 stored_properties.try_scoped_set_from_iter(scope, properties)365 })366 .map_err(<CommonError<T>>::from)?;367368 Ok(())369 }370371 372 373 374 pub fn try_mutate_token_aux_property<R, E>(375 collection_id: CollectionId,376 token_id: TokenId,377 scope: PropertyScope,378 key: PropertyKey,379 f: impl FnOnce(&mut Option<AuxPropertyValue>) -> Result<R, E>,380 ) -> Result<R, E> {381 <TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)382 }383384 385 pub fn remove_token_aux_property(386 collection_id: CollectionId,387 token_id: TokenId,388 scope: PropertyScope,389 key: PropertyKey,390 ) {391 <TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));392 }393394 395 396 397 pub fn iterate_token_aux_properties(398 collection_id: CollectionId,399 token_id: TokenId,400 scope: PropertyScope,401 ) -> impl Iterator<Item = (PropertyKey, AuxPropertyValue)> {402 <TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))403 }404405 406 pub fn current_token_id(collection_id: CollectionId) -> TokenId {407 TokenId(<TokensMinted<T>>::get(collection_id))408 }409}410411412impl<T: Config> Pallet<T> {413 414 415 416 417 418 pub fn init_collection(419 owner: T::CrossAccountId,420 payer: T::CrossAccountId,421 data: CreateCollectionData<T::AccountId>,422 flags: CollectionFlags,423 ) -> Result<CollectionId, DispatchError> {424 <PalletCommon<T>>::init_collection(owner, payer, data, flags)425 }426427 428 429 430 431 pub fn destroy_collection(432 collection: NonfungibleHandle<T>,433 sender: &T::CrossAccountId,434 ) -> DispatchResult {435 let id = collection.id;436437 if Self::collection_has_tokens(id) {438 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());439 }440441 442443 PalletCommon::destroy_collection(collection.0, sender)?;444445 let _ = <TokenData<T>>::clear_prefix((id,), u32::MAX, None);446 let _ = <TokenChildren<T>>::clear_prefix((id,), u32::MAX, None);447 let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);448 <TokensMinted<T>>::remove(id);449 <TokensBurnt<T>>::remove(id);450 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);451 let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);452 let _ = <CollectionAllowance<T>>::clear_prefix((id,), u32::MAX, None);453 Ok(())454 }455456 457 458 459 460 461 462 463 464 465 pub fn burn(466 collection: &NonfungibleHandle<T>,467 sender: &T::CrossAccountId,468 token: TokenId,469 ) -> DispatchResult {470 let token_data =471 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;472 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);473474 if collection.permissions.access() == AccessMode::AllowList {475 collection.check_allowlist(sender)?;476 }477478 if Self::token_has_children(collection.id, token) {479 return Err(<Error<T>>::CantBurnNftWithChildren.into());480 }481482 let burnt = <TokensBurnt<T>>::get(collection.id)483 .checked_add(1)484 .ok_or(ArithmeticError::Overflow)?;485486 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))487 .checked_sub(1)488 .ok_or(ArithmeticError::Overflow)?;489490 491492 if balance == 0 {493 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));494 } else {495 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);496 }497498 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);499500 <Owned<T>>::remove((collection.id, &token_data.owner, token));501 <TokensBurnt<T>>::insert(collection.id, burnt);502 <TokenData<T>>::remove((collection.id, token));503 <TokenProperties<T>>::remove((collection.id, token));504 let _ = <TokenAuxProperties<T>>::clear_prefix((collection.id, token), u32::MAX, None);505 let old_spender = <Allowance<T>>::take((collection.id, token));506507 if let Some(old_spender) = old_spender {508 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(509 collection.id,510 token,511 token_data.owner.clone(),512 old_spender,513 0,514 ));515 }516517 <PalletEvm<T>>::deposit_log(518 ERC721Events::Transfer {519 from: *token_data.owner.as_eth(),520 to: H160::default(),521 token_id: token.into(),522 }523 .to_log(collection_id_to_address(collection.id)),524 );525 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(526 collection.id,527 token,528 token_data.owner,529 1,530 ));531 Ok(())532 }533534 535 536 537 538 539 540 #[transactional]541 pub fn burn_recursively(542 collection: &NonfungibleHandle<T>,543 sender: &T::CrossAccountId,544 token: TokenId,545 self_budget: &dyn Budget,546 breadth_budget: &dyn Budget,547 ) -> DispatchResultWithPostInfo {548 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);549550 let current_token_account =551 T::CrossTokenAddressMapping::token_to_address(collection.id, token);552553 let mut weight = Weight::zero();554555 556 557 for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {558 ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);559 let PostDispatchInfo { actual_weight, .. } =560 <PalletStructure<T>>::burn_item_recursively(561 current_token_account.clone(),562 collection,563 token,564 self_budget,565 breadth_budget,566 )?;567 if let Some(actual_weight) = actual_weight {568 weight = weight.saturating_add(actual_weight);569 }570 }571572 Self::burn(collection, sender, token)?;573 DispatchResultWithPostInfo::Ok(PostDispatchInfo {574 actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),575 pays_fee: Pays::Yes,576 })577 }578579 580 581 582 583 584 585 586 587 588 589 590 591 592 #[transactional]593 fn modify_token_properties(594 collection: &NonfungibleHandle<T>,595 sender: &T::CrossAccountId,596 token_id: TokenId,597 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,598 is_token_create: bool,599 nesting_budget: &dyn Budget,600 ) -> DispatchResult {601 let is_token_owner = || {602 let is_owned = <PalletStructure<T>>::check_indirectly_owned(603 sender.clone(),604 collection.id,605 token_id,606 None,607 nesting_budget,608 )?;609610 Ok(is_owned)611 };612613 let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));614615 <PalletCommon<T>>::modify_token_properties(616 collection,617 sender,618 token_id,619 properties_updates,620 is_token_create,621 stored_properties,622 is_token_owner,623 |properties| <TokenProperties<T>>::set((collection.id, token_id), properties),624 erc::ERC721TokenEvent::TokenChanged {625 token_id: token_id.into(),626 }627 .to_log(T::ContractAddress::get()),628 )629 }630631 632 633 634 635 636 pub fn set_token_properties(637 collection: &NonfungibleHandle<T>,638 sender: &T::CrossAccountId,639 token_id: TokenId,640 properties: impl Iterator<Item = Property>,641 is_token_create: bool,642 nesting_budget: &dyn Budget,643 ) -> DispatchResult {644 Self::modify_token_properties(645 collection,646 sender,647 token_id,648 properties.map(|p| (p.key, Some(p.value))),649 is_token_create,650 nesting_budget,651 )652 }653654 655 656 657 658 659 pub fn set_token_property(660 collection: &NonfungibleHandle<T>,661 sender: &T::CrossAccountId,662 token_id: TokenId,663 property: Property,664 nesting_budget: &dyn Budget,665 ) -> DispatchResult {666 let is_token_create = false;667668 Self::set_token_properties(669 collection,670 sender,671 token_id,672 [property].into_iter(),673 is_token_create,674 nesting_budget,675 )676 }677678 679 680 681 682 683 pub fn delete_token_properties(684 collection: &NonfungibleHandle<T>,685 sender: &T::CrossAccountId,686 token_id: TokenId,687 property_keys: impl Iterator<Item = PropertyKey>,688 nesting_budget: &dyn Budget,689 ) -> DispatchResult {690 let is_token_create = false;691692 Self::modify_token_properties(693 collection,694 sender,695 token_id,696 property_keys.into_iter().map(|key| (key, None)),697 is_token_create,698 nesting_budget,699 )700 }701702 703 704 705 706 707 pub fn delete_token_property(708 collection: &NonfungibleHandle<T>,709 sender: &T::CrossAccountId,710 token_id: TokenId,711 property_key: PropertyKey,712 nesting_budget: &dyn Budget,713 ) -> DispatchResult {714 Self::delete_token_properties(715 collection,716 sender,717 token_id,718 [property_key].into_iter(),719 nesting_budget,720 )721 }722723 724 pub fn set_collection_properties(725 collection: &NonfungibleHandle<T>,726 sender: &T::CrossAccountId,727 properties: Vec<Property>,728 ) -> DispatchResult {729 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())730 }731732 733 pub fn delete_collection_properties(734 collection: &CollectionHandle<T>,735 sender: &T::CrossAccountId,736 property_keys: Vec<PropertyKey>,737 ) -> DispatchResult {738 <PalletCommon<T>>::delete_collection_properties(739 collection,740 sender,741 property_keys.into_iter(),742 )743 }744745 746 747 748 pub fn set_token_property_permissions(749 collection: &CollectionHandle<T>,750 sender: &T::CrossAccountId,751 property_permissions: Vec<PropertyKeyPermission>,752 ) -> DispatchResult {753 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)754 }755756 757 758 759 pub fn set_scoped_token_property_permissions(760 collection: &CollectionHandle<T>,761 sender: &T::CrossAccountId,762 scope: PropertyScope,763 property_permissions: Vec<PropertyKeyPermission>,764 ) -> DispatchResult {765 <PalletCommon<T>>::set_scoped_token_property_permissions(766 collection,767 sender,768 scope,769 property_permissions,770 )771 }772773 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {774 <PalletCommon<T>>::property_permissions(collection_id)775 }776777 pub fn check_token_immediate_ownership(778 collection: &NonfungibleHandle<T>,779 token: TokenId,780 possible_owner: &T::CrossAccountId,781 ) -> DispatchResult {782 let token_data =783 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;784 ensure!(785 &token_data.owner == possible_owner,786 <CommonError<T>>::NoPermission787 );788 Ok(())789 }790791 792 793 794 795 796 797 798 799 800 pub fn transfer(801 collection: &NonfungibleHandle<T>,802 from: &T::CrossAccountId,803 to: &T::CrossAccountId,804 token: TokenId,805 nesting_budget: &dyn Budget,806 ) -> DispatchResultWithPostInfo {807 ensure!(808 collection.limits.transfers_enabled(),809 <CommonError<T>>::TransferNotAllowed810 );811812 let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();813 let token_data =814 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;815 ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);816817 if collection.permissions.access() == AccessMode::AllowList {818 collection.check_allowlist(from)?;819 collection.check_allowlist(to)?;820 actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;821 }822 <PalletCommon<T>>::ensure_correct_receiver(to)?;823824 let balance_from = <AccountBalance<T>>::get((collection.id, from))825 .checked_sub(1)826 .ok_or(<CommonError<T>>::TokenValueTooLow)?;827 let balance_to = if from != to {828 let balance_to = <AccountBalance<T>>::get((collection.id, to))829 .checked_add(1)830 .ok_or(ArithmeticError::Overflow)?;831832 ensure!(833 balance_to < collection.limits.account_token_ownership_limit(),834 <CommonError<T>>::AccountTokenLimitExceeded,835 );836837 Some(balance_to)838 } else {839 None840 };841842 <PalletStructure<T>>::nest_if_sent_to_token(843 from.clone(),844 to,845 collection.id,846 token,847 nesting_budget,848 )?;849850 851852 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);853854 <TokenData<T>>::insert(855 (collection.id, token),856 ItemData {857 owner: to.clone(),858 ..token_data859 },860 );861862 if let Some(balance_to) = balance_to {863 864 if balance_from == 0 {865 <AccountBalance<T>>::remove((collection.id, from));866 } else {867 <AccountBalance<T>>::insert((collection.id, from), balance_from);868 }869 <AccountBalance<T>>::insert((collection.id, to), balance_to);870 <Owned<T>>::remove((collection.id, from, token));871 <Owned<T>>::insert((collection.id, to, token), true);872 }873 Self::set_allowance_unchecked(collection, from, token, None, true);874875 <PalletEvm<T>>::deposit_log(876 ERC721Events::Transfer {877 from: *from.as_eth(),878 to: *to.as_eth(),879 token_id: token.into(),880 }881 .to_log(collection_id_to_address(collection.id)),882 );883 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(884 collection.id,885 token,886 from.clone(),887 to.clone(),888 1,889 ));890891 Ok(PostDispatchInfo {892 actual_weight: Some(actual_weight),893 pays_fee: Pays::Yes,894 })895 }896897 898 899 900 901 902 903 904 905 906 907 pub fn create_multiple_items(908 collection: &NonfungibleHandle<T>,909 sender: &T::CrossAccountId,910 data: Vec<CreateItemData<T>>,911 nesting_budget: &dyn Budget,912 ) -> DispatchResult {913 if !collection.is_owner_or_admin(sender) {914 ensure!(915 collection.permissions.mint_mode(),916 <CommonError<T>>::PublicMintingNotAllowed917 );918 collection.check_allowlist(sender)?;919920 for item in data.iter() {921 collection.check_allowlist(&item.owner)?;922 }923 }924925 for data in data.iter() {926 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;927 }928929 let first_token = <TokensMinted<T>>::get(collection.id);930 let tokens_minted = first_token931 .checked_add(data.len() as u32)932 .ok_or(ArithmeticError::Overflow)?;933 ensure!(934 tokens_minted <= collection.limits.token_limit(),935 <CommonError<T>>::CollectionTokenLimitExceeded936 );937938 let mut balances = BTreeMap::new();939 for data in &data {940 let balance = balances941 .entry(&data.owner)942 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));943 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;944945 ensure!(946 *balance <= collection.limits.account_token_ownership_limit(),947 <CommonError<T>>::AccountTokenLimitExceeded,948 );949 }950951 for (i, data) in data.iter().enumerate() {952 let token = TokenId(first_token + i as u32 + 1);953954 <PalletStructure<T>>::check_nesting(955 sender.clone(),956 &data.owner,957 collection.id,958 token,959 nesting_budget,960 )?;961 }962963 964965 with_transaction(|| {966 for (i, data) in data.iter().enumerate() {967 let token = first_token + i as u32 + 1;968969 <TokenData<T>>::insert(970 (collection.id, token),971 ItemData {972 973 owner: data.owner.clone(),974 },975 );976977 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(978 &data.owner,979 collection.id,980 TokenId(token),981 );982983 if let Err(e) = Self::set_token_properties(984 collection,985 sender,986 TokenId(token),987 data.properties.clone().into_iter(),988 true,989 nesting_budget,990 ) {991 return TransactionOutcome::Rollback(Err(e));992 }993 }994 TransactionOutcome::Commit(Ok(()))995 })?;996997 <TokensMinted<T>>::insert(collection.id, tokens_minted);998 for (account, balance) in balances {999 <AccountBalance<T>>::insert((collection.id, account), balance);1000 }1001 for (i, data) in data.into_iter().enumerate() {1002 let token = first_token + i as u32 + 1;1003 <Owned<T>>::insert((collection.id, &data.owner, token), true);10041005 <PalletEvm<T>>::deposit_log(1006 ERC721Events::Transfer {1007 from: H160::default(),1008 to: *data.owner.as_eth(),1009 token_id: token.into(),1010 }1011 .to_log(collection_id_to_address(collection.id)),1012 );1013 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1014 collection.id,1015 TokenId(token),1016 data.owner.clone(),1017 1,1018 ));1019 }1020 Ok(())1021 }10221023 pub fn set_allowance_unchecked(1024 collection: &NonfungibleHandle<T>,1025 sender: &T::CrossAccountId,1026 token: TokenId,1027 spender: Option<&T::CrossAccountId>,1028 assume_implicit_eth: bool,1029 ) {1030 if let Some(spender) = spender {1031 let old_spender = <Allowance<T>>::get((collection.id, token));1032 <Allowance<T>>::insert((collection.id, token), spender);1033 1034 1035 <PalletEvm<T>>::deposit_log(1036 ERC721Events::Approval {1037 owner: *sender.as_eth(),1038 approved: *spender.as_eth(),1039 token_id: token.into(),1040 }1041 .to_log(collection_id_to_address(collection.id)),1042 );1043 1044 1045 if old_spender.as_ref() != Some(spender) {1046 if let Some(old_owner) = old_spender {1047 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1048 collection.id,1049 token,1050 sender.clone(),1051 old_owner,1052 0,1053 ));1054 }1055 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1056 collection.id,1057 token,1058 sender.clone(),1059 spender.clone(),1060 1,1061 ));1062 }1063 } else {1064 let old_spender = <Allowance<T>>::take((collection.id, token));1065 if !assume_implicit_eth {1066 1067 1068 <PalletEvm<T>>::deposit_log(1069 ERC721Events::Approval {1070 owner: *sender.as_eth(),1071 approved: H160::default(),1072 token_id: token.into(),1073 }1074 .to_log(collection_id_to_address(collection.id)),1075 );1076 }1077 1078 1079 if let Some(old_spender) = old_spender {1080 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1081 collection.id,1082 token,1083 sender.clone(),1084 old_spender,1085 0,1086 ));1087 }1088 }1089 }10901091 pub fn get_allowance(1092 collection: &NonfungibleHandle<T>,1093 token_id: TokenId,1094 ) -> Result<Option<T::CrossAccountId>, DispatchError> {1095 ensure!(1096 <TokenData<T>>::get((collection.id, token_id)).is_some(),1097 <CommonError<T>>::TokenNotFound1098 );1099 Ok(<Allowance<T>>::get((collection.id, token_id)))1100 }11011102 1103 1104 1105 pub fn set_allowance(1106 collection: &NonfungibleHandle<T>,1107 sender: &T::CrossAccountId,1108 token: TokenId,1109 spender: Option<&T::CrossAccountId>,1110 ) -> DispatchResult {1111 if collection.permissions.access() == AccessMode::AllowList {1112 collection.check_allowlist(sender)?;1113 if let Some(spender) = spender {1114 collection.check_allowlist(spender)?;1115 }1116 }11171118 if let Some(spender) = spender {1119 <PalletCommon<T>>::ensure_correct_receiver(spender)?;1120 }11211122 let token_data =1123 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1124 if &token_data.owner != sender {1125 ensure!(1126 collection.ignores_owned_amount(sender),1127 <CommonError<T>>::CantApproveMoreThanOwned1128 );1129 }11301131 11321133 Self::set_allowance_unchecked(collection, sender, token, spender, false);1134 Ok(())1135 }11361137 1138 1139 1140 1141 1142 pub fn set_allowance_from(1143 collection: &NonfungibleHandle<T>,1144 sender: &T::CrossAccountId,1145 from: &T::CrossAccountId,1146 token: TokenId,1147 to: Option<&T::CrossAccountId>,1148 ) -> DispatchResult {1149 if collection.permissions.access() == AccessMode::AllowList {1150 collection.check_allowlist(sender)?;1151 collection.check_allowlist(from)?;1152 if let Some(to) = to {1153 collection.check_allowlist(to)?;1154 }1155 }11561157 if let Some(to) = to {1158 <PalletCommon<T>>::ensure_correct_receiver(to)?;1159 }11601161 ensure!(1162 sender.conv_eq(from),1163 <CommonError<T>>::AddressIsNotEthMirror1164 );11651166 let token_data =1167 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1168 if token_data.owner != *from {1169 ensure!(1170 collection.limits.owner_can_transfer()1171 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),1172 <CommonError<T>>::CantApproveMoreThanOwned1173 );1174 }11751176 11771178 Self::set_allowance_unchecked(collection, from, token, to, false);1179 Ok(())1180 }11811182 1183 fn check_allowed(1184 collection: &NonfungibleHandle<T>,1185 spender: &T::CrossAccountId,1186 from: &T::CrossAccountId,1187 token: TokenId,1188 nesting_budget: &dyn Budget,1189 ) -> DispatchResult {1190 if spender.conv_eq(from) {1191 return Ok(());1192 }1193 if collection.permissions.access() == AccessMode::AllowList {1194 1195 collection.check_allowlist(spender)?;1196 }11971198 if collection.ignores_token_restrictions(spender) {1199 return Ok(());1200 }12011202 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1203 ensure!(1204 <PalletStructure<T>>::check_indirectly_owned(1205 spender.clone(),1206 source.0,1207 source.1,1208 None,1209 nesting_budget1210 )?,1211 <CommonError<T>>::ApprovedValueTooLow,1212 );1213 return Ok(());1214 }1215 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {1216 return Ok(());1217 }1218 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1219 return Ok(());1220 }12211222 Err(<CommonError<T>>::ApprovedValueTooLow.into())1223 }12241225 1226 1227 1228 1229 1230 1231 pub fn transfer_from(1232 collection: &NonfungibleHandle<T>,1233 spender: &T::CrossAccountId,1234 from: &T::CrossAccountId,1235 to: &T::CrossAccountId,1236 token: TokenId,1237 nesting_budget: &dyn Budget,1238 ) -> DispatchResultWithPostInfo {1239 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12401241 12421243 1244 let mut result = Self::transfer(collection, from, to, token, nesting_budget);1245 add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::checks_allowed_raw());1246 result1247 }12481249 1250 1251 1252 1253 1254 1255 pub fn burn_from(1256 collection: &NonfungibleHandle<T>,1257 spender: &T::CrossAccountId,1258 from: &T::CrossAccountId,1259 token: TokenId,1260 nesting_budget: &dyn Budget,1261 ) -> DispatchResult {1262 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12631264 12651266 Self::burn(collection, from, token)1267 }12681269 1270 1271 pub fn check_nesting(1272 handle: &NonfungibleHandle<T>,1273 sender: T::CrossAccountId,1274 from: (CollectionId, TokenId),1275 under: TokenId,1276 nesting_budget: &dyn Budget,1277 ) -> DispatchResult {1278 let nesting = handle.permissions.nesting();12791280 #[cfg(not(feature = "runtime-benchmarks"))]1281 let permissive = false;1282 #[cfg(feature = "runtime-benchmarks")]1283 let permissive = nesting.permissive;12841285 if permissive {1286 ensure!(1287 <TokenData<T>>::contains_key((handle.id, under)),1288 <CommonError<T>>::TokenNotFound1289 );1290 } else if nesting.token_owner1291 && <PalletStructure<T>>::check_indirectly_owned(1292 sender.clone(),1293 handle.id,1294 under,1295 Some(from),1296 nesting_budget,1297 )? {1298 1299 } else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {1300 1301 let _ = <PalletStructure<T>>::get_checked_topmost_owner(1302 handle.id,1303 under,1304 Some(from),1305 nesting_budget,1306 )?1307 .ok_or(<CommonError<T>>::TokenNotFound)?;1308 } else {1309 fail!(<CommonError<T>>::UserIsNotAllowedToNest);1310 }13111312 if let Some(whitelist) = &nesting.restricted {1313 ensure!(1314 whitelist.contains(&from.0),1315 <CommonError<T>>::SourceCollectionIsNotAllowedToNest1316 );1317 }1318 Ok(())1319 }13201321 fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {1322 <TokenChildren<T>>::insert((under.0, under.1, (to_nest.0, to_nest.1)), true);1323 }13241325 fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1326 <TokenChildren<T>>::remove((under.0, under.1, to_unnest));1327 }13281329 fn collection_has_tokens(collection_id: CollectionId) -> bool {1330 <TokenData<T>>::iter_prefix((collection_id,))1331 .next()1332 .is_some()1333 }13341335 fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1336 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1337 .next()1338 .is_some()1339 }13401341 pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1342 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1343 .map(|((child_collection_id, child_id), _)| TokenChild {1344 collection: child_collection_id,1345 token: child_id,1346 })1347 .collect()1348 }13491350 1351 1352 1353 1354 1355 pub fn create_item(1356 collection: &NonfungibleHandle<T>,1357 sender: &T::CrossAccountId,1358 data: CreateItemData<T>,1359 nesting_budget: &dyn Budget,1360 ) -> DispatchResult {1361 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1362 }13631364 1365 1366 1367 1368 1369 1370 pub fn set_allowance_for_all(1371 collection: &NonfungibleHandle<T>,1372 owner: &T::CrossAccountId,1373 operator: &T::CrossAccountId,1374 approve: bool,1375 ) -> DispatchResult {1376 <PalletCommon<T>>::set_allowance_for_all(1377 collection,1378 owner,1379 operator,1380 approve,1381 || <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve),1382 ERC721Events::ApprovalForAll {1383 owner: *owner.as_eth(),1384 operator: *operator.as_eth(),1385 approved: approve,1386 }1387 .to_log(collection_id_to_address(collection.id)),1388 )1389 }13901391 1392 pub fn allowance_for_all(1393 collection: &NonfungibleHandle<T>,1394 owner: &T::CrossAccountId,1395 operator: &T::CrossAccountId,1396 ) -> bool {1397 <CollectionAllowance<T>>::get((collection.id, owner, operator))1398 }13991400 pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {1401 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1402 properties.recompute_consumed_space();1403 });14041405 Ok(())1406 }1407}