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 weights::{PostDispatchInfo, Pays},101};102use up_data_structs::{103 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,104 mapping::TokenAddressMapping, budget::Budget, Property, PropertyPermission, PropertyKey,105 PropertyValue, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty, TokenChild,106 AuxPropertyValue,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,112};113use pallet_structure::{Pallet as PalletStructure, Error as StructureError};114use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};115use sp_core::H160;116use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};117use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap, collections::btree_set::BTreeSet};118use core::ops::Deref;119use codec::{Encode, Decode, MaxEncodedLen};120use scale_info::TypeInfo;121122pub use pallet::*;123use weights::WeightInfo;124#[cfg(feature = "runtime-benchmarks")]125pub mod benchmarking;126pub mod common;127pub mod erc;128pub mod weights;129130pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;131pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;132133134135#[struct_versioning::versioned(version = 2, upper)]136#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]137pub struct ItemData<CrossAccountId> {138 #[version(..2)]139 pub const_data: BoundedVec<u8, CustomDataLimit>,140141 #[version(..2)]142 pub variable_data: BoundedVec<u8, CustomDataLimit>,143144 pub owner: CrossAccountId,145}146147#[frame_support::pallet]148pub mod pallet {149 use super::*;150 use frame_support::{151 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,152 };153 use frame_system::pallet_prelude::*;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 #[pallet::generate_store(pub(super) trait Store)]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 = Properties,205 QueryKind = ValueQuery,206 OnEmpty = up_data_structs::TokenProperties,207 >;208209 210 211 212 213 214 215 216 217 218 #[pallet::storage]219 #[pallet::getter(fn token_aux_property)]220 pub type TokenAuxProperties<T: Config> = StorageNMap<221 Key = (222 Key<Twox64Concat, CollectionId>,223 Key<Twox64Concat, TokenId>,224 Key<Twox64Concat, PropertyScope>,225 Key<Twox64Concat, PropertyKey>,226 ),227 Value = AuxPropertyValue,228 QueryKind = OptionQuery,229 >;230231 232 #[pallet::storage]233 pub type Owned<T: Config> = StorageNMap<234 Key = (235 Key<Twox64Concat, CollectionId>,236 Key<Blake2_128Concat, T::CrossAccountId>,237 Key<Twox64Concat, TokenId>,238 ),239 Value = bool,240 QueryKind = ValueQuery,241 >;242243 244 #[pallet::storage]245 #[pallet::getter(fn token_children)]246 pub type TokenChildren<T: Config> = StorageNMap<247 Key = (248 Key<Twox64Concat, CollectionId>,249 Key<Twox64Concat, TokenId>,250 Key<Twox64Concat, (CollectionId, TokenId)>,251 ),252 Value = bool,253 QueryKind = ValueQuery,254 >;255256 257 #[pallet::storage]258 pub type AccountBalance<T: Config> = StorageNMap<259 Key = (260 Key<Twox64Concat, CollectionId>,261 Key<Blake2_128Concat, T::CrossAccountId>,262 ),263 Value = u32,264 QueryKind = ValueQuery,265 >;266267 268 #[pallet::storage]269 pub type Allowance<T: Config> = StorageNMap<270 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),271 Value = T::CrossAccountId,272 QueryKind = OptionQuery,273 >;274275 276 #[pallet::hooks]277 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {278 fn on_runtime_upgrade() -> Weight {279 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {280 let mut had_consts = BTreeSet::new();281 <TokenData<T>>::translate::<ItemDataVersion1<T::CrossAccountId>, _>(282 |(collection, token), v| {283 let mut props = vec![];284 if !v.const_data.is_empty() {285 props.push(Property {286 key: b"_old_constData".to_vec().try_into().unwrap(),287 value: v288 .const_data289 .clone()290 .into_inner()291 .try_into()292 .expect("const too long"),293 });294 had_consts.insert(collection);295 }296 if !v.variable_data.is_empty() {297 props.push(Property {298 key: b"_old_variableData".to_vec().try_into().unwrap(),299 value: v300 .variable_data301 .clone()302 .into_inner()303 .try_into()304 .expect("variable too long"),305 })306 }307 if !props.is_empty() {308 Self::set_scoped_token_properties(309 collection,310 token,311 PropertyScope::None,312 props.into_iter(),313 )314 .expect("existing token data exceeds property storage");315 }316 Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))317 },318 );319 for collection in had_consts {320 <PalletCommon<T>>::set_property_permission_unchecked(321 collection,322 PropertyKeyPermission {323 key: b"_old_constData".to_vec().try_into().unwrap(),324 permission: PropertyPermission {325 mutable: false,326 collection_admin: true,327 token_owner: false,328 },329 },330 )331 .expect("failed to configure permission");332 }333 }334335 0336 }337 }338}339340pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);341impl<T: Config> NonfungibleHandle<T> {342 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {343 Self(inner)344 }345 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {346 self.0347 }348 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {349 &mut self.0350 }351}352impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {353 fn recorder(&self) -> &SubstrateRecorder<T> {354 self.0.recorder()355 }356 fn into_recorder(self) -> SubstrateRecorder<T> {357 self.0.into_recorder()358 }359}360impl<T: Config> Deref for NonfungibleHandle<T> {361 type Target = pallet_common::CollectionHandle<T>;362363 fn deref(&self) -> &Self::Target {364 &self.0365 }366}367368impl<T: Config> Pallet<T> {369 370 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {371 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)372 }373374 375 376 377 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {378 <TokenData<T>>::contains_key((collection.id, token))379 }380381 382 383 384 pub fn set_scoped_token_property(385 collection_id: CollectionId,386 token_id: TokenId,387 scope: PropertyScope,388 property: Property,389 ) -> DispatchResult {390 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {391 properties.try_scoped_set(scope, property.key, property.value)392 })393 .map_err(<CommonError<T>>::from)?;394395 Ok(())396 }397398 399 pub fn set_scoped_token_properties(400 collection_id: CollectionId,401 token_id: TokenId,402 scope: PropertyScope,403 properties: impl Iterator<Item = Property>,404 ) -> DispatchResult {405 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {406 stored_properties.try_scoped_set_from_iter(scope, properties)407 })408 .map_err(<CommonError<T>>::from)?;409410 Ok(())411 }412413 414 415 416 pub fn try_mutate_token_aux_property<R, E>(417 collection_id: CollectionId,418 token_id: TokenId,419 scope: PropertyScope,420 key: PropertyKey,421 f: impl FnOnce(&mut Option<AuxPropertyValue>) -> Result<R, E>,422 ) -> Result<R, E> {423 <TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)424 }425426 427 pub fn remove_token_aux_property(428 collection_id: CollectionId,429 token_id: TokenId,430 scope: PropertyScope,431 key: PropertyKey,432 ) {433 <TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));434 }435436 437 438 439 pub fn iterate_token_aux_properties(440 collection_id: CollectionId,441 token_id: TokenId,442 scope: PropertyScope,443 ) -> impl Iterator<Item = (PropertyKey, AuxPropertyValue)> {444 <TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))445 }446447 448 pub fn current_token_id(collection_id: CollectionId) -> TokenId {449 TokenId(<TokensMinted<T>>::get(collection_id))450 }451}452453454impl<T: Config> Pallet<T> {455 456 457 458 459 460 pub fn init_collection(461 owner: T::CrossAccountId,462 data: CreateCollectionData<T::AccountId>,463 is_external: bool,464 ) -> Result<CollectionId, DispatchError> {465 <PalletCommon<T>>::init_collection(owner, data, is_external)466 }467468 469 470 471 472 pub fn destroy_collection(473 collection: NonfungibleHandle<T>,474 sender: &T::CrossAccountId,475 ) -> DispatchResult {476 let id = collection.id;477478 if Self::collection_has_tokens(id) {479 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());480 }481482 483484 PalletCommon::destroy_collection(collection.0, sender)?;485486 <TokenData<T>>::remove_prefix((id,), None);487 <TokenChildren<T>>::remove_prefix((id,), None);488 <Owned<T>>::remove_prefix((id,), None);489 <TokensMinted<T>>::remove(id);490 <TokensBurnt<T>>::remove(id);491 <Allowance<T>>::remove_prefix((id,), None);492 <AccountBalance<T>>::remove_prefix((id,), None);493 Ok(())494 }495496 497 498 499 500 501 502 503 504 505 pub fn burn(506 collection: &NonfungibleHandle<T>,507 sender: &T::CrossAccountId,508 token: TokenId,509 ) -> DispatchResult {510 let token_data =511 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;512 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);513514 if collection.permissions.access() == AccessMode::AllowList {515 collection.check_allowlist(sender)?;516 }517518 if Self::token_has_children(collection.id, token) {519 return Err(<Error<T>>::CantBurnNftWithChildren.into());520 }521522 let burnt = <TokensBurnt<T>>::get(collection.id)523 .checked_add(1)524 .ok_or(ArithmeticError::Overflow)?;525526 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))527 .checked_sub(1)528 .ok_or(ArithmeticError::Overflow)?;529530 531532 if balance == 0 {533 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));534 } else {535 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);536 }537538 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);539540 <Owned<T>>::remove((collection.id, &token_data.owner, token));541 <TokensBurnt<T>>::insert(collection.id, burnt);542 <TokenData<T>>::remove((collection.id, token));543 <TokenProperties<T>>::remove((collection.id, token));544 <TokenAuxProperties<T>>::remove_prefix((collection.id, token), None);545 let old_spender = <Allowance<T>>::take((collection.id, token));546547 if let Some(old_spender) = old_spender {548 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(549 collection.id,550 token,551 token_data.owner.clone(),552 old_spender,553 0,554 ));555 }556557 <PalletEvm<T>>::deposit_log(558 ERC721Events::Transfer {559 from: *token_data.owner.as_eth(),560 to: H160::default(),561 token_id: token.into(),562 }563 .to_log(collection_id_to_address(collection.id)),564 );565 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(566 collection.id,567 token,568 token_data.owner,569 1,570 ));571 Ok(())572 }573574 575 576 577 578 579 580 #[transactional]581 pub fn burn_recursively(582 collection: &NonfungibleHandle<T>,583 sender: &T::CrossAccountId,584 token: TokenId,585 self_budget: &dyn Budget,586 breadth_budget: &dyn Budget,587 ) -> DispatchResultWithPostInfo {588 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);589590 let current_token_account =591 T::CrossTokenAddressMapping::token_to_address(collection.id, token);592593 let mut weight = 0 as Weight;594595 596 597 for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {598 ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);599 let PostDispatchInfo { actual_weight, .. } =600 <PalletStructure<T>>::burn_item_recursively(601 current_token_account.clone(),602 collection,603 token,604 self_budget,605 breadth_budget,606 )?;607 if let Some(actual_weight) = actual_weight {608 weight = weight.saturating_add(actual_weight);609 }610 }611612 Self::burn(collection, sender, token)?;613 DispatchResultWithPostInfo::Ok(PostDispatchInfo {614 actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),615 pays_fee: Pays::Yes,616 })617 }618619 620 621 622 623 624 625 626 627 #[transactional]628 fn modify_token_properties(629 collection: &NonfungibleHandle<T>,630 sender: &T::CrossAccountId,631 token_id: TokenId,632 properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,633 is_token_create: bool,634 nesting_budget: &dyn Budget,635 ) -> DispatchResult {636 let mut collection_admin_status = None;637 let mut token_owner_result = None;638639 let mut is_collection_admin =640 || *collection_admin_status.get_or_insert_with(|| collection.is_owner_or_admin(sender));641642 let mut is_token_owner = || {643 *token_owner_result.get_or_insert_with(|| -> Result<bool, DispatchError> {644 let is_owned = <PalletStructure<T>>::check_indirectly_owned(645 sender.clone(),646 collection.id,647 token_id,648 None,649 nesting_budget,650 )?;651652 Ok(is_owned)653 })654 };655656 for (key, value) in properties {657 let permission = <PalletCommon<T>>::property_permissions(collection.id)658 .get(&key)659 .cloned()660 .unwrap_or_else(PropertyPermission::none);661662 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))663 .get(&key)664 .is_some();665666 match permission {667 PropertyPermission { mutable: false, .. } if is_property_exists => {668 return Err(<CommonError<T>>::NoPermission.into());669 }670671 PropertyPermission {672 collection_admin,673 token_owner,674 ..675 } => {676 677 if is_token_create && (collection_admin || token_owner) && value.is_some() {678 679 } else if collection_admin && is_collection_admin() {680 681 } else if token_owner && is_token_owner()? {682 683 } else {684 fail!(<CommonError<T>>::NoPermission);685 }686 }687 }688689 match value {690 Some(value) => {691 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {692 properties.try_set(key.clone(), value)693 })694 .map_err(<CommonError<T>>::from)?;695696 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(697 collection.id,698 token_id,699 key,700 ));701 }702 None => {703 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {704 properties.remove(&key)705 })706 .map_err(<CommonError<T>>::from)?;707708 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(709 collection.id,710 token_id,711 key,712 ));713 }714 }715 }716717 Ok(())718 }719720 721 722 723 724 725 pub fn set_token_properties(726 collection: &NonfungibleHandle<T>,727 sender: &T::CrossAccountId,728 token_id: TokenId,729 properties: impl Iterator<Item = Property>,730 is_token_create: bool,731 nesting_budget: &dyn Budget,732 ) -> DispatchResult {733 Self::modify_token_properties(734 collection,735 sender,736 token_id,737 properties.map(|p| (p.key, Some(p.value))),738 is_token_create,739 nesting_budget,740 )741 }742743 744 745 746 747 748 pub fn set_token_property(749 collection: &NonfungibleHandle<T>,750 sender: &T::CrossAccountId,751 token_id: TokenId,752 property: Property,753 nesting_budget: &dyn Budget,754 ) -> DispatchResult {755 let is_token_create = false;756757 Self::set_token_properties(758 collection,759 sender,760 token_id,761 [property].into_iter(),762 is_token_create,763 nesting_budget,764 )765 }766767 768 769 770 771 772 pub fn delete_token_properties(773 collection: &NonfungibleHandle<T>,774 sender: &T::CrossAccountId,775 token_id: TokenId,776 property_keys: impl Iterator<Item = PropertyKey>,777 nesting_budget: &dyn Budget,778 ) -> DispatchResult {779 let is_token_create = false;780781 Self::modify_token_properties(782 collection,783 sender,784 token_id,785 property_keys.into_iter().map(|key| (key, None)),786 is_token_create,787 nesting_budget,788 )789 }790791 792 793 794 795 796 pub fn delete_token_property(797 collection: &NonfungibleHandle<T>,798 sender: &T::CrossAccountId,799 token_id: TokenId,800 property_key: PropertyKey,801 nesting_budget: &dyn Budget,802 ) -> DispatchResult {803 Self::delete_token_properties(804 collection,805 sender,806 token_id,807 [property_key].into_iter(),808 nesting_budget,809 )810 }811812 813 pub fn set_collection_properties(814 collection: &NonfungibleHandle<T>,815 sender: &T::CrossAccountId,816 properties: Vec<Property>,817 ) -> DispatchResult {818 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)819 }820821 822 pub fn delete_collection_properties(823 collection: &CollectionHandle<T>,824 sender: &T::CrossAccountId,825 property_keys: Vec<PropertyKey>,826 ) -> DispatchResult {827 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)828 }829830 831 832 833 pub fn set_token_property_permissions(834 collection: &CollectionHandle<T>,835 sender: &T::CrossAccountId,836 property_permissions: Vec<PropertyKeyPermission>,837 ) -> DispatchResult {838 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)839 }840841 842 843 844 pub fn set_property_permission(845 collection: &CollectionHandle<T>,846 sender: &T::CrossAccountId,847 permission: PropertyKeyPermission,848 ) -> DispatchResult {849 <PalletCommon<T>>::set_property_permission(collection, sender, permission)850 }851852 853 854 855 856 857 858 859 860 861 pub fn transfer(862 collection: &NonfungibleHandle<T>,863 from: &T::CrossAccountId,864 to: &T::CrossAccountId,865 token: TokenId,866 nesting_budget: &dyn Budget,867 ) -> DispatchResult {868 ensure!(869 collection.limits.transfers_enabled(),870 <CommonError<T>>::TransferNotAllowed871 );872873 let token_data =874 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;875 ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);876877 if collection.permissions.access() == AccessMode::AllowList {878 collection.check_allowlist(from)?;879 collection.check_allowlist(to)?;880 }881 <PalletCommon<T>>::ensure_correct_receiver(to)?;882883 let balance_from = <AccountBalance<T>>::get((collection.id, from))884 .checked_sub(1)885 .ok_or(<CommonError<T>>::TokenValueTooLow)?;886 let balance_to = if from != to {887 let balance_to = <AccountBalance<T>>::get((collection.id, to))888 .checked_add(1)889 .ok_or(ArithmeticError::Overflow)?;890891 ensure!(892 balance_to < collection.limits.account_token_ownership_limit(),893 <CommonError<T>>::AccountTokenLimitExceeded,894 );895896 Some(balance_to)897 } else {898 None899 };900901 <PalletStructure<T>>::nest_if_sent_to_token(902 from.clone(),903 to,904 collection.id,905 token,906 nesting_budget,907 )?;908909 910911 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);912913 <TokenData<T>>::insert(914 (collection.id, token),915 ItemData {916 owner: to.clone(),917 ..token_data918 },919 );920921 if let Some(balance_to) = balance_to {922 923 if balance_from == 0 {924 <AccountBalance<T>>::remove((collection.id, from));925 } else {926 <AccountBalance<T>>::insert((collection.id, from), balance_from);927 }928 <AccountBalance<T>>::insert((collection.id, to), balance_to);929 <Owned<T>>::remove((collection.id, from, token));930 <Owned<T>>::insert((collection.id, to, token), true);931 }932 Self::set_allowance_unchecked(collection, from, token, None, true);933934 <PalletEvm<T>>::deposit_log(935 ERC721Events::Transfer {936 from: *from.as_eth(),937 to: *to.as_eth(),938 token_id: token.into(),939 }940 .to_log(collection_id_to_address(collection.id)),941 );942 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(943 collection.id,944 token,945 from.clone(),946 to.clone(),947 1,948 ));949 Ok(())950 }951952 953 954 955 956 957 958 959 960 961 962 pub fn create_multiple_items(963 collection: &NonfungibleHandle<T>,964 sender: &T::CrossAccountId,965 data: Vec<CreateItemData<T>>,966 nesting_budget: &dyn Budget,967 ) -> DispatchResult {968 if !collection.is_owner_or_admin(sender) {969 ensure!(970 collection.permissions.mint_mode(),971 <CommonError<T>>::PublicMintingNotAllowed972 );973 collection.check_allowlist(sender)?;974975 for item in data.iter() {976 collection.check_allowlist(&item.owner)?;977 }978 }979980 for data in data.iter() {981 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;982 }983984 let first_token = <TokensMinted<T>>::get(collection.id);985 let tokens_minted = first_token986 .checked_add(data.len() as u32)987 .ok_or(ArithmeticError::Overflow)?;988 ensure!(989 tokens_minted <= collection.limits.token_limit(),990 <CommonError<T>>::CollectionTokenLimitExceeded991 );992993 let mut balances = BTreeMap::new();994 for data in &data {995 let balance = balances996 .entry(&data.owner)997 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));998 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;9991000 ensure!(1001 *balance <= collection.limits.account_token_ownership_limit(),1002 <CommonError<T>>::AccountTokenLimitExceeded,1003 );1004 }10051006 for (i, data) in data.iter().enumerate() {1007 let token = TokenId(first_token + i as u32 + 1);10081009 <PalletStructure<T>>::check_nesting(1010 sender.clone(),1011 &data.owner,1012 collection.id,1013 token,1014 nesting_budget,1015 )?;1016 }10171018 10191020 with_transaction(|| {1021 for (i, data) in data.iter().enumerate() {1022 let token = first_token + i as u32 + 1;10231024 <TokenData<T>>::insert(1025 (collection.id, token),1026 ItemData {1027 1028 owner: data.owner.clone(),1029 },1030 );10311032 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(1033 &data.owner,1034 collection.id,1035 TokenId(token),1036 );10371038 if let Err(e) = Self::set_token_properties(1039 collection,1040 sender,1041 TokenId(token),1042 data.properties.clone().into_iter(),1043 true,1044 nesting_budget,1045 ) {1046 return TransactionOutcome::Rollback(Err(e));1047 }1048 }1049 TransactionOutcome::Commit(Ok(()))1050 })?;10511052 <TokensMinted<T>>::insert(collection.id, tokens_minted);1053 for (account, balance) in balances {1054 <AccountBalance<T>>::insert((collection.id, account), balance);1055 }1056 for (i, data) in data.into_iter().enumerate() {1057 let token = first_token + i as u32 + 1;1058 <Owned<T>>::insert((collection.id, &data.owner, token), true);10591060 <PalletEvm<T>>::deposit_log(1061 ERC721Events::Transfer {1062 from: H160::default(),1063 to: *data.owner.as_eth(),1064 token_id: token.into(),1065 }1066 .to_log(collection_id_to_address(collection.id)),1067 );1068 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1069 collection.id,1070 TokenId(token),1071 data.owner.clone(),1072 1,1073 ));1074 }1075 Ok(())1076 }10771078 pub fn set_allowance_unchecked(1079 collection: &NonfungibleHandle<T>,1080 sender: &T::CrossAccountId,1081 token: TokenId,1082 spender: Option<&T::CrossAccountId>,1083 assume_implicit_eth: bool,1084 ) {1085 if let Some(spender) = spender {1086 let old_spender = <Allowance<T>>::get((collection.id, token));1087 <Allowance<T>>::insert((collection.id, token), spender);1088 1089 1090 <PalletEvm<T>>::deposit_log(1091 ERC721Events::Approval {1092 owner: *sender.as_eth(),1093 approved: *spender.as_eth(),1094 token_id: token.into(),1095 }1096 .to_log(collection_id_to_address(collection.id)),1097 );1098 1099 1100 if old_spender.as_ref() != Some(spender) {1101 if let Some(old_owner) = old_spender {1102 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1103 collection.id,1104 token,1105 sender.clone(),1106 old_owner,1107 0,1108 ));1109 }1110 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1111 collection.id,1112 token,1113 sender.clone(),1114 spender.clone(),1115 1,1116 ));1117 }1118 } else {1119 let old_spender = <Allowance<T>>::take((collection.id, token));1120 if !assume_implicit_eth {1121 1122 1123 <PalletEvm<T>>::deposit_log(1124 ERC721Events::Approval {1125 owner: *sender.as_eth(),1126 approved: H160::default(),1127 token_id: token.into(),1128 }1129 .to_log(collection_id_to_address(collection.id)),1130 );1131 }1132 1133 1134 if let Some(old_spender) = old_spender {1135 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1136 collection.id,1137 token,1138 sender.clone(),1139 old_spender,1140 0,1141 ));1142 }1143 }1144 }11451146 1147 1148 1149 pub fn set_allowance(1150 collection: &NonfungibleHandle<T>,1151 sender: &T::CrossAccountId,1152 token: TokenId,1153 spender: Option<&T::CrossAccountId>,1154 ) -> DispatchResult {1155 if collection.permissions.access() == AccessMode::AllowList {1156 collection.check_allowlist(sender)?;1157 if let Some(spender) = spender {1158 collection.check_allowlist(spender)?;1159 }1160 }11611162 if let Some(spender) = spender {1163 <PalletCommon<T>>::ensure_correct_receiver(spender)?;1164 }11651166 let token_data =1167 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1168 if &token_data.owner != sender {1169 ensure!(1170 collection.ignores_owned_amount(sender),1171 <CommonError<T>>::CantApproveMoreThanOwned1172 );1173 }11741175 11761177 Self::set_allowance_unchecked(collection, sender, token, spender, false);1178 Ok(())1179 }11801181 1182 fn check_allowed(1183 collection: &NonfungibleHandle<T>,1184 spender: &T::CrossAccountId,1185 from: &T::CrossAccountId,1186 token: TokenId,1187 nesting_budget: &dyn Budget,1188 ) -> DispatchResult {1189 if spender.conv_eq(from) {1190 return Ok(());1191 }1192 if collection.permissions.access() == AccessMode::AllowList {1193 1194 collection.check_allowlist(spender)?;1195 }11961197 if collection.limits.owner_can_transfer() && collection.is_owner_or_admin(spender) {1198 return Ok(());1199 }12001201 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1202 ensure!(1203 <PalletStructure<T>>::check_indirectly_owned(1204 spender.clone(),1205 source.0,1206 source.1,1207 None,1208 nesting_budget1209 )?,1210 <CommonError<T>>::ApprovedValueTooLow,1211 );1212 return Ok(());1213 }1214 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {1215 return Ok(());1216 }1217 ensure!(1218 collection.ignores_allowance(spender),1219 <CommonError<T>>::ApprovedValueTooLow1220 );1221 Ok(())1222 }12231224 1225 1226 1227 1228 1229 1230 pub fn transfer_from(1231 collection: &NonfungibleHandle<T>,1232 spender: &T::CrossAccountId,1233 from: &T::CrossAccountId,1234 to: &T::CrossAccountId,1235 token: TokenId,1236 nesting_budget: &dyn Budget,1237 ) -> DispatchResult {1238 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12391240 12411242 1243 Self::transfer(collection, from, to, token, nesting_budget)1244 }12451246 1247 1248 1249 1250 1251 1252 pub fn burn_from(1253 collection: &NonfungibleHandle<T>,1254 spender: &T::CrossAccountId,1255 from: &T::CrossAccountId,1256 token: TokenId,1257 nesting_budget: &dyn Budget,1258 ) -> DispatchResult {1259 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12601261 12621263 Self::burn(collection, from, token)1264 }12651266 1267 1268 pub fn check_nesting(1269 handle: &NonfungibleHandle<T>,1270 sender: T::CrossAccountId,1271 from: (CollectionId, TokenId),1272 under: TokenId,1273 nesting_budget: &dyn Budget,1274 ) -> DispatchResult {1275 let nesting = handle.permissions.nesting();12761277 #[cfg(not(feature = "runtime-benchmarks"))]1278 let permissive = false;1279 #[cfg(feature = "runtime-benchmarks")]1280 let permissive = nesting.permissive;12811282 if permissive {1283 1284 } else if nesting.token_owner1285 && <PalletStructure<T>>::check_indirectly_owned(1286 sender.clone(),1287 handle.id,1288 under,1289 Some(from),1290 nesting_budget,1291 )? {1292 1293 } else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {1294 1295 } else {1296 fail!(<CommonError<T>>::UserIsNotAllowedToNest);1297 }12981299 if let Some(whitelist) = &nesting.restricted {1300 ensure!(1301 whitelist.contains(&from.0),1302 <CommonError<T>>::SourceCollectionIsNotAllowedToNest1303 );1304 }1305 Ok(())1306 }13071308 fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {1309 <TokenChildren<T>>::insert((under.0, under.1, (to_nest.0, to_nest.1)), true);1310 }13111312 fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1313 <TokenChildren<T>>::remove((under.0, under.1, to_unnest));1314 }13151316 fn collection_has_tokens(collection_id: CollectionId) -> bool {1317 <TokenData<T>>::iter_prefix((collection_id,))1318 .next()1319 .is_some()1320 }13211322 fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1323 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1324 .next()1325 .is_some()1326 }13271328 pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1329 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1330 .map(|((child_collection_id, child_id), _)| TokenChild {1331 collection: child_collection_id,1332 token: child_id,1333 })1334 .collect()1335 }13361337 1338 1339 1340 1341 1342 pub fn create_item(1343 collection: &NonfungibleHandle<T>,1344 sender: &T::CrossAccountId,1345 data: CreateItemData<T>,1346 nesting_budget: &dyn Budget,1347 ) -> DispatchResult {1348 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1349 }1350}