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,112};113use pallet_structure::{Pallet as PalletStructure, Error as StructureError};114use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};115use sp_core::{Get, H160};116use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};117use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};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::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 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::AccountId>,428 flags: CollectionFlags,429 ) -> Result<CollectionId, DispatchError> {430 <PalletCommon<T>>::init_collection(owner, payer, data, flags)431 }432433 434 435 436 437 pub fn destroy_collection(438 collection: NonfungibleHandle<T>,439 sender: &T::CrossAccountId,440 ) -> DispatchResult {441 let id = collection.id;442443 if Self::collection_has_tokens(id) {444 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());445 }446447 448449 PalletCommon::destroy_collection(collection.0, sender)?;450451 let _ = <TokenData<T>>::clear_prefix((id,), u32::MAX, None);452 let _ = <TokenChildren<T>>::clear_prefix((id,), u32::MAX, None);453 let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);454 <TokensMinted<T>>::remove(id);455 <TokensBurnt<T>>::remove(id);456 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);457 let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);458 let _ = <CollectionAllowance<T>>::clear_prefix((id,), u32::MAX, None);459 Ok(())460 }461462 463 464 465 466 467 468 469 470 471 pub fn burn(472 collection: &NonfungibleHandle<T>,473 sender: &T::CrossAccountId,474 token: TokenId,475 ) -> DispatchResult {476 let token_data =477 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;478 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);479480 if collection.permissions.access() == AccessMode::AllowList {481 collection.check_allowlist(sender)?;482 }483484 if Self::token_has_children(collection.id, token) {485 return Err(<Error<T>>::CantBurnNftWithChildren.into());486 }487488 let burnt = <TokensBurnt<T>>::get(collection.id)489 .checked_add(1)490 .ok_or(ArithmeticError::Overflow)?;491492 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))493 .checked_sub(1)494 .ok_or(ArithmeticError::Overflow)?;495496 497498 if balance == 0 {499 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));500 } else {501 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);502 }503504 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);505506 <Owned<T>>::remove((collection.id, &token_data.owner, token));507 <TokensBurnt<T>>::insert(collection.id, burnt);508 <TokenData<T>>::remove((collection.id, token));509 <TokenProperties<T>>::remove((collection.id, token));510 let _ = <TokenAuxProperties<T>>::clear_prefix((collection.id, token), u32::MAX, None);511 let old_spender = <Allowance<T>>::take((collection.id, token));512513 if let Some(old_spender) = old_spender {514 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(515 collection.id,516 token,517 token_data.owner.clone(),518 old_spender,519 0,520 ));521 }522523 <PalletEvm<T>>::deposit_log(524 ERC721Events::Transfer {525 from: *token_data.owner.as_eth(),526 to: H160::default(),527 token_id: token.into(),528 }529 .to_log(collection_id_to_address(collection.id)),530 );531 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(532 collection.id,533 token,534 token_data.owner,535 1,536 ));537 Ok(())538 }539540 541 542 543 544 545 546 #[transactional]547 pub fn burn_recursively(548 collection: &NonfungibleHandle<T>,549 sender: &T::CrossAccountId,550 token: TokenId,551 self_budget: &dyn Budget,552 breadth_budget: &dyn Budget,553 ) -> DispatchResultWithPostInfo {554 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);555556 let current_token_account =557 T::CrossTokenAddressMapping::token_to_address(collection.id, token);558559 let mut weight = Weight::zero();560561 562 563 for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {564 ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);565 let PostDispatchInfo { actual_weight, .. } =566 <PalletStructure<T>>::burn_item_recursively(567 current_token_account.clone(),568 collection,569 token,570 self_budget,571 breadth_budget,572 )?;573 if let Some(actual_weight) = actual_weight {574 weight = weight.saturating_add(actual_weight);575 }576 }577578 Self::burn(collection, sender, token)?;579 DispatchResultWithPostInfo::Ok(PostDispatchInfo {580 actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),581 pays_fee: Pays::Yes,582 })583 }584585 586 587 588 589 590 591 592 593 594 595 596 597 598 #[transactional]599 fn modify_token_properties(600 collection: &NonfungibleHandle<T>,601 sender: &T::CrossAccountId,602 token_id: TokenId,603 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,604 is_token_create: bool,605 nesting_budget: &dyn Budget,606 ) -> DispatchResult {607 let is_token_owner = || {608 let is_owned = <PalletStructure<T>>::check_indirectly_owned(609 sender.clone(),610 collection.id,611 token_id,612 None,613 nesting_budget,614 )?;615616 Ok(is_owned)617 };618619 let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));620621 <PalletCommon<T>>::modify_token_properties(622 collection,623 sender,624 token_id,625 properties_updates,626 is_token_create,627 stored_properties,628 is_token_owner,629 |properties| <TokenProperties<T>>::set((collection.id, token_id), properties),630 erc::ERC721TokenEvent::TokenChanged {631 token_id: token_id.into(),632 }633 .to_log(T::ContractAddress::get()),634 )635 }636637 638 639 640 641 642 pub fn set_token_properties(643 collection: &NonfungibleHandle<T>,644 sender: &T::CrossAccountId,645 token_id: TokenId,646 properties: impl Iterator<Item = Property>,647 is_token_create: bool,648 nesting_budget: &dyn Budget,649 ) -> DispatchResult {650 Self::modify_token_properties(651 collection,652 sender,653 token_id,654 properties.map(|p| (p.key, Some(p.value))),655 is_token_create,656 nesting_budget,657 )658 }659660 661 662 663 664 665 pub fn set_token_property(666 collection: &NonfungibleHandle<T>,667 sender: &T::CrossAccountId,668 token_id: TokenId,669 property: Property,670 nesting_budget: &dyn Budget,671 ) -> DispatchResult {672 let is_token_create = false;673674 Self::set_token_properties(675 collection,676 sender,677 token_id,678 [property].into_iter(),679 is_token_create,680 nesting_budget,681 )682 }683684 685 686 687 688 689 pub fn delete_token_properties(690 collection: &NonfungibleHandle<T>,691 sender: &T::CrossAccountId,692 token_id: TokenId,693 property_keys: impl Iterator<Item = PropertyKey>,694 nesting_budget: &dyn Budget,695 ) -> DispatchResult {696 let is_token_create = false;697698 Self::modify_token_properties(699 collection,700 sender,701 token_id,702 property_keys.into_iter().map(|key| (key, None)),703 is_token_create,704 nesting_budget,705 )706 }707708 709 710 711 712 713 pub fn delete_token_property(714 collection: &NonfungibleHandle<T>,715 sender: &T::CrossAccountId,716 token_id: TokenId,717 property_key: PropertyKey,718 nesting_budget: &dyn Budget,719 ) -> DispatchResult {720 Self::delete_token_properties(721 collection,722 sender,723 token_id,724 [property_key].into_iter(),725 nesting_budget,726 )727 }728729 730 pub fn set_collection_properties(731 collection: &NonfungibleHandle<T>,732 sender: &T::CrossAccountId,733 properties: Vec<Property>,734 ) -> DispatchResult {735 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())736 }737738 739 pub fn delete_collection_properties(740 collection: &CollectionHandle<T>,741 sender: &T::CrossAccountId,742 property_keys: Vec<PropertyKey>,743 ) -> DispatchResult {744 <PalletCommon<T>>::delete_collection_properties(745 collection,746 sender,747 property_keys.into_iter(),748 )749 }750751 752 753 754 pub fn set_token_property_permissions(755 collection: &CollectionHandle<T>,756 sender: &T::CrossAccountId,757 property_permissions: Vec<PropertyKeyPermission>,758 ) -> DispatchResult {759 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)760 }761762 763 764 765 pub fn set_scoped_token_property_permissions(766 collection: &CollectionHandle<T>,767 sender: &T::CrossAccountId,768 scope: PropertyScope,769 property_permissions: Vec<PropertyKeyPermission>,770 ) -> DispatchResult {771 <PalletCommon<T>>::set_scoped_token_property_permissions(772 collection,773 sender,774 scope,775 property_permissions,776 )777 }778779 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {780 <PalletCommon<T>>::property_permissions(collection_id)781 }782783 pub fn check_token_immediate_ownership(784 collection: &NonfungibleHandle<T>,785 token: TokenId,786 possible_owner: &T::CrossAccountId,787 ) -> DispatchResult {788 let token_data =789 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;790 ensure!(791 &token_data.owner == possible_owner,792 <CommonError<T>>::NoPermission793 );794 Ok(())795 }796797 798 799 800 801 802 803 804 805 806 pub fn transfer(807 collection: &NonfungibleHandle<T>,808 from: &T::CrossAccountId,809 to: &T::CrossAccountId,810 token: TokenId,811 nesting_budget: &dyn Budget,812 ) -> DispatchResult {813 ensure!(814 collection.limits.transfers_enabled(),815 <CommonError<T>>::TransferNotAllowed816 );817818 let token_data =819 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;820 ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);821822 if collection.permissions.access() == AccessMode::AllowList {823 collection.check_allowlist(from)?;824 collection.check_allowlist(to)?;825 }826 <PalletCommon<T>>::ensure_correct_receiver(to)?;827828 let balance_from = <AccountBalance<T>>::get((collection.id, from))829 .checked_sub(1)830 .ok_or(<CommonError<T>>::TokenValueTooLow)?;831 let balance_to = if from != to {832 let balance_to = <AccountBalance<T>>::get((collection.id, to))833 .checked_add(1)834 .ok_or(ArithmeticError::Overflow)?;835836 ensure!(837 balance_to < collection.limits.account_token_ownership_limit(),838 <CommonError<T>>::AccountTokenLimitExceeded,839 );840841 Some(balance_to)842 } else {843 None844 };845846 <PalletStructure<T>>::nest_if_sent_to_token(847 from.clone(),848 to,849 collection.id,850 token,851 nesting_budget,852 )?;853854 855856 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);857858 <TokenData<T>>::insert(859 (collection.id, token),860 ItemData {861 owner: to.clone(),862 ..token_data863 },864 );865866 if let Some(balance_to) = balance_to {867 868 if balance_from == 0 {869 <AccountBalance<T>>::remove((collection.id, from));870 } else {871 <AccountBalance<T>>::insert((collection.id, from), balance_from);872 }873 <AccountBalance<T>>::insert((collection.id, to), balance_to);874 <Owned<T>>::remove((collection.id, from, token));875 <Owned<T>>::insert((collection.id, to, token), true);876 }877 Self::set_allowance_unchecked(collection, from, token, None, true);878879 <PalletEvm<T>>::deposit_log(880 ERC721Events::Transfer {881 from: *from.as_eth(),882 to: *to.as_eth(),883 token_id: token.into(),884 }885 .to_log(collection_id_to_address(collection.id)),886 );887 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(888 collection.id,889 token,890 from.clone(),891 to.clone(),892 1,893 ));894 Ok(())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 ) -> DispatchResult {1239 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12401241 12421243 1244 Self::transfer(collection, from, to, token, nesting_budget)1245 }12461247 1248 1249 1250 1251 1252 1253 pub fn burn_from(1254 collection: &NonfungibleHandle<T>,1255 spender: &T::CrossAccountId,1256 from: &T::CrossAccountId,1257 token: TokenId,1258 nesting_budget: &dyn Budget,1259 ) -> DispatchResult {1260 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12611262 12631264 Self::burn(collection, from, token)1265 }12661267 1268 1269 pub fn check_nesting(1270 handle: &NonfungibleHandle<T>,1271 sender: T::CrossAccountId,1272 from: (CollectionId, TokenId),1273 under: TokenId,1274 nesting_budget: &dyn Budget,1275 ) -> DispatchResult {1276 let nesting = handle.permissions.nesting();12771278 #[cfg(not(feature = "runtime-benchmarks"))]1279 let permissive = false;1280 #[cfg(feature = "runtime-benchmarks")]1281 let permissive = nesting.permissive;12821283 if permissive {1284 ensure!(1285 <TokenData<T>>::contains_key((handle.id, under)),1286 <CommonError<T>>::TokenNotFound1287 );1288 } else if nesting.token_owner1289 && <PalletStructure<T>>::check_indirectly_owned(1290 sender.clone(),1291 handle.id,1292 under,1293 Some(from),1294 nesting_budget,1295 )? {1296 1297 } else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {1298 1299 let _ = <PalletStructure<T>>::get_checked_topmost_owner(1300 handle.id,1301 under,1302 Some(from),1303 nesting_budget,1304 )?1305 .ok_or(<CommonError<T>>::TokenNotFound)?;1306 } else {1307 fail!(<CommonError<T>>::UserIsNotAllowedToNest);1308 }13091310 if let Some(whitelist) = &nesting.restricted {1311 ensure!(1312 whitelist.contains(&from.0),1313 <CommonError<T>>::SourceCollectionIsNotAllowedToNest1314 );1315 }1316 Ok(())1317 }13181319 fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {1320 <TokenChildren<T>>::insert((under.0, under.1, (to_nest.0, to_nest.1)), true);1321 }13221323 fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1324 <TokenChildren<T>>::remove((under.0, under.1, to_unnest));1325 }13261327 fn collection_has_tokens(collection_id: CollectionId) -> bool {1328 <TokenData<T>>::iter_prefix((collection_id,))1329 .next()1330 .is_some()1331 }13321333 fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1334 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1335 .next()1336 .is_some()1337 }13381339 pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1340 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1341 .map(|((child_collection_id, child_id), _)| TokenChild {1342 collection: child_collection_id,1343 token: child_id,1344 })1345 .collect()1346 }13471348 1349 1350 1351 1352 1353 pub fn create_item(1354 collection: &NonfungibleHandle<T>,1355 sender: &T::CrossAccountId,1356 data: CreateItemData<T>,1357 nesting_budget: &dyn Budget,1358 ) -> DispatchResult {1359 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1360 }13611362 1363 1364 1365 1366 1367 1368 pub fn set_allowance_for_all(1369 collection: &NonfungibleHandle<T>,1370 owner: &T::CrossAccountId,1371 operator: &T::CrossAccountId,1372 approve: bool,1373 ) -> DispatchResult {1374 <PalletCommon<T>>::set_allowance_for_all(1375 collection,1376 owner,1377 operator,1378 approve,1379 || <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve),1380 ERC721Events::ApprovalForAll {1381 owner: *owner.as_eth(),1382 operator: *operator.as_eth(),1383 approved: approve,1384 }1385 .to_log(collection_id_to_address(collection.id)),1386 )1387 }13881389 1390 pub fn allowance_for_all(1391 collection: &NonfungibleHandle<T>,1392 owner: &T::CrossAccountId,1393 operator: &T::CrossAccountId,1394 ) -> bool {1395 <CollectionAllowance<T>>::get((collection.id, owner, operator))1396 }13971398 pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {1399 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1400 properties.recompute_consumed_space();1401 });14021403 Ok(())1404 }1405}