12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788#![cfg_attr(not(feature = "std"), no_std)]8990use crate::erc_token::ERC20Events;91use crate::erc::ERC721Events;9293use core::ops::Deref;94use evm_coder::ToLog;95use frame_support::{ensure, storage::with_transaction, transactional};96use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};97use pallet_evm_coder_substrate::WithRecorder;98use pallet_common::{99 CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,100 Event as CommonEvent, Pallet as PalletCommon,101};102use pallet_structure::Pallet as PalletStructure;103use sp_core::{Get, H160};104use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};105use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};106use up_data_structs::{107 AccessMode, budget::Budget, CollectionId, CollectionFlags, CreateCollectionData,108 mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, Property, PropertyKey,109 PropertyKeyPermission, PropertyScope, PropertyValue, TokenId, TrySetProperty,110 PropertiesPermissionMap, CreateRefungibleExMultipleOwners, TokenOwnerError,111 TokenProperties as TokenPropertiesT,112};113114pub use pallet::*;115#[cfg(feature = "runtime-benchmarks")]116pub mod benchmarking;117pub mod common;118pub mod erc;119pub mod erc_token;120pub mod weights;121122pub type CreateItemData<T> =123 CreateRefungibleExMultipleOwners<<T as pallet_evm::Config>::CrossAccountId>;124pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;125126#[frame_support::pallet]127pub mod pallet {128 use super::*;129 use frame_support::{130 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,131 traits::StorageVersion,132 };133 use up_data_structs::{CollectionId, TokenId};134 use super::weights::WeightInfo;135136 #[pallet::error]137 pub enum Error<T> {138 139 NotRefungibleDataUsedToMintFungibleCollectionToken,140 141 WrongRefungiblePieces,142 143 RepartitionWhileNotOwningAllPieces,144 145 RefungibleDisallowsNesting,146 147 SettingPropertiesNotAllowed,148 }149150 #[pallet::config]151 pub trait Config:152 frame_system::Config + pallet_common::Config + pallet_structure::Config153 {154 type WeightInfo: WeightInfo;155 }156157 const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);158159 #[pallet::pallet]160 #[pallet::storage_version(STORAGE_VERSION)]161 #[pallet::generate_store(pub(super) trait Store)]162 pub struct Pallet<T>(_);163164 165 #[pallet::storage]166 pub type TokensMinted<T: Config> =167 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;168169 170 #[pallet::storage]171 pub type TokensBurnt<T: Config> =172 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;173174 175 #[pallet::storage]176 #[pallet::getter(fn token_properties)]177 pub type TokenProperties<T: Config> = StorageNMap<178 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),179 Value = TokenPropertiesT,180 QueryKind = ValueQuery,181 >;182183 184 #[pallet::storage]185 pub type TotalSupply<T: Config> = StorageNMap<186 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),187 Value = u128,188 QueryKind = ValueQuery,189 >;190191 192 #[pallet::storage]193 pub type Owned<T: Config> = StorageNMap<194 Key = (195 Key<Twox64Concat, CollectionId>,196 Key<Blake2_128Concat, T::CrossAccountId>,197 Key<Twox64Concat, TokenId>,198 ),199 Value = bool,200 QueryKind = ValueQuery,201 >;202203 204 #[pallet::storage]205 pub type AccountBalance<T: Config> = StorageNMap<206 Key = (207 Key<Twox64Concat, CollectionId>,208 209 Key<Blake2_128Concat, T::CrossAccountId>,210 ),211 Value = u32,212 QueryKind = ValueQuery,213 >;214215 216 #[pallet::storage]217 pub type Balance<T: Config> = StorageNMap<218 Key = (219 Key<Twox64Concat, CollectionId>,220 Key<Twox64Concat, TokenId>,221 222 Key<Blake2_128Concat, T::CrossAccountId>,223 ),224 Value = u128,225 QueryKind = ValueQuery,226 >;227228 229 #[pallet::storage]230 pub type Allowance<T: Config> = StorageNMap<231 Key = (232 Key<Twox64Concat, CollectionId>,233 Key<Twox64Concat, TokenId>,234 235 Key<Blake2_128, T::CrossAccountId>,236 237 Key<Blake2_128Concat, T::CrossAccountId>,238 ),239 Value = u128,240 QueryKind = ValueQuery,241 >;242243 244 #[pallet::storage]245 pub type CollectionAllowance<T: Config> = StorageNMap<246 Key = (247 Key<Twox64Concat, CollectionId>,248 Key<Blake2_128Concat, T::CrossAccountId>, 249 Key<Blake2_128Concat, T::CrossAccountId>, 250 ),251 Value = bool,252 QueryKind = ValueQuery,253 >;254}255256pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);257impl<T: Config> RefungibleHandle<T> {258 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {259 Self(inner)260 }261 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {262 self.0263 }264 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {265 &mut self.0266 }267}268269impl<T: Config> Deref for RefungibleHandle<T> {270 type Target = pallet_common::CollectionHandle<T>;271272 fn deref(&self) -> &Self::Target {273 &self.0274 }275}276277impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {278 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {279 self.0.recorder()280 }281 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {282 self.0.into_recorder()283 }284}285286impl<T: Config> Pallet<T> {287 288 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {289 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)290 }291292 293 294 295 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {296 <TotalSupply<T>>::contains_key((collection.id, token))297 }298299 pub fn set_scoped_token_property(300 collection_id: CollectionId,301 token_id: TokenId,302 scope: PropertyScope,303 property: Property,304 ) -> DispatchResult {305 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {306 properties.try_scoped_set(scope, property.key, property.value)307 })308 .map_err(<CommonError<T>>::from)?;309310 Ok(())311 }312313 pub fn set_scoped_token_properties(314 collection_id: CollectionId,315 token_id: TokenId,316 scope: PropertyScope,317 properties: impl Iterator<Item = Property>,318 ) -> DispatchResult {319 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {320 stored_properties.try_scoped_set_from_iter(scope, properties)321 })322 .map_err(<CommonError<T>>::from)?;323324 Ok(())325 }326}327328329impl<T: Config> Pallet<T> {330 331 332 333 334 335 pub fn init_collection(336 owner: T::CrossAccountId,337 payer: T::CrossAccountId,338 data: CreateCollectionData<T::AccountId>,339 flags: CollectionFlags,340 ) -> Result<CollectionId, DispatchError> {341 <PalletCommon<T>>::init_collection(owner, payer, data, flags)342 }343344 345 346 347 348 pub fn destroy_collection(349 collection: RefungibleHandle<T>,350 sender: &T::CrossAccountId,351 ) -> DispatchResult {352 let id = collection.id;353354 if Self::collection_has_tokens(id) {355 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());356 }357358 359360 PalletCommon::destroy_collection(collection.0, sender)?;361362 <TokensMinted<T>>::remove(id);363 <TokensBurnt<T>>::remove(id);364 let _ = <TotalSupply<T>>::clear_prefix((id,), u32::MAX, None);365 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);366 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);367 let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);368 let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);369 Ok(())370 }371372 fn collection_has_tokens(collection_id: CollectionId) -> bool {373 <TotalSupply<T>>::iter_prefix((collection_id,))374 .next()375 .is_some()376 }377378 pub fn burn_token_unchecked(379 collection: &RefungibleHandle<T>,380 owner: &T::CrossAccountId,381 token_id: TokenId,382 ) -> DispatchResult {383 let burnt = <TokensBurnt<T>>::get(collection.id)384 .checked_add(1)385 .ok_or(ArithmeticError::Overflow)?;386387 <TokensBurnt<T>>::insert(collection.id, burnt);388 <TokenProperties<T>>::remove((collection.id, token_id));389 <TotalSupply<T>>::remove((collection.id, token_id));390 let _ = <Balance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);391 let _ = <Allowance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);392 <PalletEvm<T>>::deposit_log(393 ERC721Events::Transfer {394 from: *owner.as_eth(),395 to: H160::default(),396 token_id: token_id.into(),397 }398 .to_log(collection_id_to_address(collection.id)),399 );400 Ok(())401 }402403 404 405 406 407 408 409 410 411 412 413 414 pub fn burn(415 collection: &RefungibleHandle<T>,416 owner: &T::CrossAccountId,417 token: TokenId,418 amount: u128,419 ) -> DispatchResult {420 if <Balance<T>>::get((collection.id, token, owner)) == 0 {421 return Err(<CommonError<T>>::TokenValueTooLow.into());422 }423424 let total_supply = <TotalSupply<T>>::get((collection.id, token))425 .checked_sub(amount)426 .ok_or(<CommonError<T>>::TokenValueTooLow)?;427428 429 if total_supply == 0 {430 431 ensure!(432 <Balance<T>>::get((collection.id, token, owner)) == amount,433 <CommonError<T>>::TokenValueTooLow434 );435 let account_balance = <AccountBalance<T>>::get((collection.id, owner))436 .checked_sub(1)437 438 .ok_or(ArithmeticError::Underflow)?;439440 441442 <Owned<T>>::remove((collection.id, owner, token));443 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);444 <AccountBalance<T>>::insert((collection.id, owner), account_balance);445 Self::burn_token_unchecked(collection, owner, token)?;446 <PalletEvm<T>>::deposit_log(447 ERC20Events::Transfer {448 from: *owner.as_eth(),449 to: H160::default(),450 value: amount.into(),451 }452 .to_log(collection_id_to_address(collection.id)),453 );454 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(455 collection.id,456 token,457 owner.clone(),458 amount,459 ));460 return Ok(());461 }462463 let balance = <Balance<T>>::get((collection.id, token, owner))464 .checked_sub(amount)465 .ok_or(<CommonError<T>>::TokenValueTooLow)?;466 let account_balance = if balance == 0 {467 <AccountBalance<T>>::get((collection.id, owner))468 .checked_sub(1)469 470 .ok_or(ArithmeticError::Underflow)?471 } else {472 0473 };474475 476477 if balance == 0 {478 <Owned<T>>::remove((collection.id, owner, token));479 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);480 <Balance<T>>::remove((collection.id, token, owner));481 <AccountBalance<T>>::insert((collection.id, owner), account_balance);482483 if let Ok(user) = Self::token_owner(collection.id, token) {484 <PalletEvm<T>>::deposit_log(485 ERC721Events::Transfer {486 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,487 to: *user.as_eth(),488 token_id: token.into(),489 }490 .to_log(collection_id_to_address(collection.id)),491 );492 }493 } else {494 <Balance<T>>::insert((collection.id, token, owner), balance);495 }496 <TotalSupply<T>>::insert((collection.id, token), total_supply);497498 <PalletEvm<T>>::deposit_log(499 ERC20Events::Transfer {500 from: *owner.as_eth(),501 to: H160::default(),502 value: amount.into(),503 }504 .to_log(T::EvmTokenAddressMapping::token_to_address(505 collection.id,506 token,507 )),508 );509 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(510 collection.id,511 token,512 owner.clone(),513 amount,514 ));515 Ok(())516 }517518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 #[transactional]536 fn modify_token_properties(537 collection: &RefungibleHandle<T>,538 sender: &T::CrossAccountId,539 token_id: TokenId,540 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,541 is_token_create: bool,542 nesting_budget: &dyn Budget,543 ) -> DispatchResult {544 let is_token_owner = || -> Result<bool, DispatchError> {545 let balance = collection.balance(sender.clone(), token_id);546 let total_pieces: u128 =547 Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);548 if balance != total_pieces {549 return Ok(false);550 }551552 let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(553 sender.clone(),554 collection.id,555 token_id,556 None,557 nesting_budget,558 )?;559560 Ok(is_bundle_owner)561 };562563 let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));564565 <PalletCommon<T>>::modify_token_properties(566 collection,567 sender,568 token_id,569 properties_updates,570 is_token_create,571 stored_properties,572 is_token_owner,573 |properties| <TokenProperties<T>>::set((collection.id, token_id), properties),574 erc::ERC721TokenEvent::TokenChanged {575 token_id: token_id.into(),576 }577 .to_log(T::ContractAddress::get()),578 )579 }580581 pub fn set_token_properties(582 collection: &RefungibleHandle<T>,583 sender: &T::CrossAccountId,584 token_id: TokenId,585 properties: impl Iterator<Item = Property>,586 is_token_create: bool,587 nesting_budget: &dyn Budget,588 ) -> DispatchResult {589 Self::modify_token_properties(590 collection,591 sender,592 token_id,593 properties.map(|p| (p.key, Some(p.value))),594 is_token_create,595 nesting_budget,596 )597 }598599 pub fn set_token_property(600 collection: &RefungibleHandle<T>,601 sender: &T::CrossAccountId,602 token_id: TokenId,603 property: Property,604 nesting_budget: &dyn Budget,605 ) -> DispatchResult {606 let is_token_create = false;607608 Self::set_token_properties(609 collection,610 sender,611 token_id,612 [property].into_iter(),613 is_token_create,614 nesting_budget,615 )616 }617618 pub fn delete_token_properties(619 collection: &RefungibleHandle<T>,620 sender: &T::CrossAccountId,621 token_id: TokenId,622 property_keys: impl Iterator<Item = PropertyKey>,623 nesting_budget: &dyn Budget,624 ) -> DispatchResult {625 let is_token_create = false;626627 Self::modify_token_properties(628 collection,629 sender,630 token_id,631 property_keys.into_iter().map(|key| (key, None)),632 is_token_create,633 nesting_budget,634 )635 }636637 pub fn delete_token_property(638 collection: &RefungibleHandle<T>,639 sender: &T::CrossAccountId,640 token_id: TokenId,641 property_key: PropertyKey,642 nesting_budget: &dyn Budget,643 ) -> DispatchResult {644 Self::delete_token_properties(645 collection,646 sender,647 token_id,648 [property_key].into_iter(),649 nesting_budget,650 )651 }652653 654 655 656 657 658 659 660 661 662 pub fn transfer(663 collection: &RefungibleHandle<T>,664 from: &T::CrossAccountId,665 to: &T::CrossAccountId,666 token: TokenId,667 amount: u128,668 nesting_budget: &dyn Budget,669 ) -> DispatchResult {670 ensure!(671 collection.limits.transfers_enabled(),672 <CommonError<T>>::TransferNotAllowed673 );674675 if collection.permissions.access() == AccessMode::AllowList {676 collection.check_allowlist(from)?;677 collection.check_allowlist(to)?;678 }679 <PalletCommon<T>>::ensure_correct_receiver(to)?;680681 let initial_balance_from = <Balance<T>>::get((collection.id, token, from));682683 if initial_balance_from == 0 {684 return Err(<CommonError<T>>::TokenValueTooLow.into());685 }686687 let updated_balance_from = initial_balance_from688 .checked_sub(amount)689 .ok_or(<CommonError<T>>::TokenValueTooLow)?;690 let mut create_target = false;691 let from_to_differ = from != to;692 let updated_balance_to = if from != to && amount != 0 {693 let old_balance = <Balance<T>>::get((collection.id, token, to));694 if old_balance == 0 {695 create_target = true;696 }697 Some(698 old_balance699 .checked_add(amount)700 .ok_or(ArithmeticError::Overflow)?,701 )702 } else {703 None704 };705706 let account_balance_from = if updated_balance_from == 0 {707 Some(708 <AccountBalance<T>>::get((collection.id, from))709 .checked_sub(1)710 711 .ok_or(ArithmeticError::Underflow)?,712 )713 } else {714 None715 };716 717 718 let account_balance_to = if create_target && from_to_differ {719 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))720 .checked_add(1)721 .ok_or(ArithmeticError::Overflow)?;722 ensure!(723 account_balance_to < collection.limits.account_token_ownership_limit(),724 <CommonError<T>>::AccountTokenLimitExceeded,725 );726727 Some(account_balance_to)728 } else {729 None730 };731732 733734 if let Some(updated_balance_to) = updated_balance_to {735 736737 <PalletStructure<T>>::nest_if_sent_to_token(738 from.clone(),739 to,740 collection.id,741 token,742 nesting_budget,743 )?;744745 if updated_balance_from == 0 {746 <Balance<T>>::remove((collection.id, token, from));747 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);748 } else {749 <Balance<T>>::insert((collection.id, token, from), updated_balance_from);750 }751 <Balance<T>>::insert((collection.id, token, to), updated_balance_to);752 if let Some(account_balance_from) = account_balance_from {753 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);754 <Owned<T>>::remove((collection.id, from, token));755 }756 if let Some(account_balance_to) = account_balance_to {757 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);758 <Owned<T>>::insert((collection.id, to, token), true);759 }760 }761762 <PalletEvm<T>>::deposit_log(763 ERC20Events::Transfer {764 from: *from.as_eth(),765 to: *to.as_eth(),766 value: amount.into(),767 }768 .to_log(T::EvmTokenAddressMapping::token_to_address(769 collection.id,770 token,771 )),772 );773774 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(775 collection.id,776 token,777 from.clone(),778 to.clone(),779 amount,780 ));781782 let total_supply = <TotalSupply<T>>::get((collection.id, token));783784 if amount == total_supply {785 786 <PalletEvm<T>>::deposit_log(787 ERC721Events::Transfer {788 from: *from.as_eth(),789 to: *to.as_eth(),790 token_id: token.into(),791 }792 .to_log(collection_id_to_address(collection.id)),793 );794 } else if let Some(updated_balance_to) = updated_balance_to {795 796 797 if initial_balance_from == total_supply {798 799 800 <PalletEvm<T>>::deposit_log(801 ERC721Events::Transfer {802 from: *from.as_eth(),803 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,804 token_id: token.into(),805 }806 .to_log(collection_id_to_address(collection.id)),807 );808 } else if updated_balance_to == total_supply {809 810 <PalletEvm<T>>::deposit_log(811 ERC721Events::Transfer {812 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,813 to: *to.as_eth(),814 token_id: token.into(),815 }816 .to_log(collection_id_to_address(collection.id)),817 );818 }819 }820821 Ok(())822 }823824 825 826 827 828 829 pub fn create_multiple_items(830 collection: &RefungibleHandle<T>,831 sender: &T::CrossAccountId,832 data: Vec<CreateItemData<T>>,833 nesting_budget: &dyn Budget,834 ) -> DispatchResult {835 if !collection.is_owner_or_admin(sender) {836 ensure!(837 collection.permissions.mint_mode(),838 <CommonError<T>>::PublicMintingNotAllowed839 );840 collection.check_allowlist(sender)?;841842 for item in data.iter() {843 for user in item.users.keys() {844 collection.check_allowlist(user)?;845 }846 }847 }848849 for item in data.iter() {850 for (owner, _) in item.users.iter() {851 <PalletCommon<T>>::ensure_correct_receiver(owner)?;852 }853 }854855 856 let totals = data857 .iter()858 .map(|data| {859 Ok(data860 .users861 .iter()862 .map(|u| u.1)863 .try_fold(0u128, |acc, v| acc.checked_add(*v))864 .ok_or(ArithmeticError::Overflow)?)865 })866 .collect::<Result<Vec<_>, DispatchError>>()?;867 for total in &totals {868 ensure!(869 *total <= MAX_REFUNGIBLE_PIECES,870 <Error<T>>::WrongRefungiblePieces871 );872 }873874 let first_token_id = <TokensMinted<T>>::get(collection.id);875 let tokens_minted = first_token_id876 .checked_add(data.len() as u32)877 .ok_or(ArithmeticError::Overflow)?;878 ensure!(879 tokens_minted < collection.limits.token_limit(),880 <CommonError<T>>::CollectionTokenLimitExceeded881 );882883 let mut balances = BTreeMap::new();884 for data in &data {885 for owner in data.users.keys() {886 let balance = balances887 .entry(owner)888 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));889 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;890891 ensure!(892 *balance <= collection.limits.account_token_ownership_limit(),893 <CommonError<T>>::AccountTokenLimitExceeded,894 );895 }896 }897898 for (i, token) in data.iter().enumerate() {899 let token_id = TokenId(first_token_id + i as u32 + 1);900 for (to, _) in token.users.iter() {901 <PalletStructure<T>>::check_nesting(902 sender.clone(),903 to,904 collection.id,905 token_id,906 nesting_budget,907 )?;908 }909 }910911 912913 with_transaction(|| {914 for (i, data) in data.iter().enumerate() {915 let token_id = first_token_id + i as u32 + 1;916 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);917918 for (user, amount) in data.users.iter() {919 if *amount == 0 {920 continue;921 }922 <Balance<T>>::insert((collection.id, token_id, &user), amount);923 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);924 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(925 user,926 collection.id,927 TokenId(token_id),928 );929 }930931 if let Err(e) = Self::set_token_properties(932 collection,933 sender,934 TokenId(token_id),935 data.properties.clone().into_iter(),936 true,937 nesting_budget,938 ) {939 return TransactionOutcome::Rollback(Err(e));940 }941 }942 TransactionOutcome::Commit(Ok(()))943 })?;944945 <TokensMinted<T>>::insert(collection.id, tokens_minted);946947 for (account, balance) in balances {948 <AccountBalance<T>>::insert((collection.id, account), balance);949 }950951 for (i, token) in data.into_iter().enumerate() {952 let token_id = first_token_id + i as u32 + 1;953954 let receivers = token955 .users956 .into_iter()957 .filter(|(_, amount)| *amount > 0)958 .collect::<Vec<_>>();959960 if let [(user, _)] = receivers.as_slice() {961 962 <PalletEvm<T>>::deposit_log(963 ERC721Events::Transfer {964 from: H160::default(),965 to: *user.as_eth(),966 token_id: token_id.into(),967 }968 .to_log(collection_id_to_address(collection.id)),969 );970 } else if let [_, ..] = receivers.as_slice() {971 972 <PalletEvm<T>>::deposit_log(973 ERC721Events::Transfer {974 from: H160::default(),975 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,976 token_id: token_id.into(),977 }978 .to_log(collection_id_to_address(collection.id)),979 );980 }981982 for (user, amount) in receivers.into_iter() {983 <PalletEvm<T>>::deposit_log(984 ERC20Events::Transfer {985 from: H160::default(),986 to: *user.as_eth(),987 value: amount.into(),988 }989 .to_log(T::EvmTokenAddressMapping::token_to_address(990 collection.id,991 TokenId(token_id),992 )),993 );994 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(995 collection.id,996 TokenId(token_id),997 user,998 amount,999 ));1000 }1001 }1002 Ok(())1003 }10041005 pub fn set_allowance_unchecked(1006 collection: &RefungibleHandle<T>,1007 sender: &T::CrossAccountId,1008 spender: &T::CrossAccountId,1009 token: TokenId,1010 amount: u128,1011 ) {1012 if amount == 0 {1013 <Allowance<T>>::remove((collection.id, token, sender, spender));1014 } else {1015 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);1016 }10171018 <PalletEvm<T>>::deposit_log(1019 ERC20Events::Approval {1020 owner: *sender.as_eth(),1021 spender: *spender.as_eth(),1022 value: amount.into(),1023 }1024 .to_log(T::EvmTokenAddressMapping::token_to_address(1025 collection.id,1026 token,1027 )),1028 );1029 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1030 collection.id,1031 token,1032 sender.clone(),1033 spender.clone(),1034 amount,1035 ))1036 }10371038 1039 1040 1041 pub fn set_allowance(1042 collection: &RefungibleHandle<T>,1043 sender: &T::CrossAccountId,1044 spender: &T::CrossAccountId,1045 token: TokenId,1046 amount: u128,1047 ) -> DispatchResult {1048 if collection.permissions.access() == AccessMode::AllowList {1049 collection.check_allowlist(sender)?;1050 collection.check_allowlist(spender)?;1051 }10521053 <PalletCommon<T>>::ensure_correct_receiver(spender)?;10541055 if <Balance<T>>::get((collection.id, token, sender)) < amount {1056 ensure!(1057 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1058 <CommonError<T>>::CantApproveMoreThanOwned1059 );1060 }10611062 10631064 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1065 Ok(())1066 }10671068 1069 1070 1071 1072 1073 pub fn set_allowance_from(1074 collection: &RefungibleHandle<T>,1075 sender: &T::CrossAccountId,1076 from: &T::CrossAccountId,1077 to: &T::CrossAccountId,1078 token_id: TokenId,1079 amount: u128,1080 ) -> DispatchResult {1081 if collection.permissions.access() == AccessMode::AllowList {1082 collection.check_allowlist(sender)?;1083 collection.check_allowlist(from)?;1084 collection.check_allowlist(to)?;1085 }10861087 <PalletCommon<T>>::ensure_correct_receiver(to)?;10881089 ensure!(1090 sender.conv_eq(from),1091 <CommonError<T>>::AddressIsNotEthMirror1092 );10931094 if <Balance<T>>::get((collection.id, token_id, from)) < amount {1095 ensure!(1096 collection.limits.owner_can_transfer()1097 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1098 && Self::token_exists(collection, token_id),1099 <CommonError<T>>::CantApproveMoreThanOwned1100 );1101 }11021103 11041105 Self::set_allowance_unchecked(collection, from, to, token_id, amount);1106 Ok(())1107 }11081109 1110 fn check_allowed(1111 collection: &RefungibleHandle<T>,1112 spender: &T::CrossAccountId,1113 from: &T::CrossAccountId,1114 token: TokenId,1115 amount: u128,1116 nesting_budget: &dyn Budget,1117 ) -> Result<Option<u128>, DispatchError> {1118 if spender.conv_eq(from) {1119 return Ok(None);1120 }1121 if collection.permissions.access() == AccessMode::AllowList {1122 1123 collection.check_allowlist(spender)?;1124 }11251126 if collection.ignores_token_restrictions(spender) {1127 return Ok(Self::compute_allowance_decrease(1128 collection, token, from, &spender, amount,1129 ));1130 }11311132 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1133 1134 ensure!(1135 <PalletStructure<T>>::check_indirectly_owned(1136 spender.clone(),1137 source.0,1138 source.1,1139 None,1140 nesting_budget1141 )?,1142 <CommonError<T>>::ApprovedValueTooLow,1143 );1144 return Ok(None);1145 }11461147 let allowance = Self::compute_allowance_decrease(collection, token, from, &spender, amount);1148 if allowance.is_some() {1149 return Ok(allowance);1150 }11511152 1153 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1154 return Ok(allowance);1155 }11561157 Err(<CommonError<T>>::ApprovedValueTooLow.into())1158 }11591160 1161 1162 fn compute_allowance_decrease(1163 collection: &RefungibleHandle<T>,1164 token: TokenId,1165 from: &T::CrossAccountId,1166 spender: &T::CrossAccountId,1167 amount: u128,1168 ) -> Option<u128> {1169 <Allowance<T>>::get((collection.id, token, from, spender)).checked_sub(amount)1170 }11711172 1173 1174 1175 1176 1177 1178 pub fn transfer_from(1179 collection: &RefungibleHandle<T>,1180 spender: &T::CrossAccountId,1181 from: &T::CrossAccountId,1182 to: &T::CrossAccountId,1183 token: TokenId,1184 amount: u128,1185 nesting_budget: &dyn Budget,1186 ) -> DispatchResult {1187 let allowance =1188 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11891190 11911192 Self::transfer(collection, from, to, token, amount, nesting_budget)?;1193 if let Some(allowance) = allowance {1194 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1195 }1196 Ok(())1197 }11981199 1200 1201 1202 1203 1204 1205 pub fn burn_from(1206 collection: &RefungibleHandle<T>,1207 spender: &T::CrossAccountId,1208 from: &T::CrossAccountId,1209 token: TokenId,1210 amount: u128,1211 nesting_budget: &dyn Budget,1212 ) -> DispatchResult {1213 let allowance =1214 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12151216 12171218 Self::burn(collection, from, token, amount)?;1219 if let Some(allowance) = allowance {1220 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1221 }1222 Ok(())1223 }12241225 1226 1227 1228 1229 1230 1231 1232 pub fn create_item(1233 collection: &RefungibleHandle<T>,1234 sender: &T::CrossAccountId,1235 data: CreateItemData<T>,1236 nesting_budget: &dyn Budget,1237 ) -> DispatchResult {1238 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1239 }12401241 1242 1243 1244 1245 1246 1247 1248 pub fn repartition(1249 collection: &RefungibleHandle<T>,1250 owner: &T::CrossAccountId,1251 token: TokenId,1252 amount: u128,1253 ) -> DispatchResult {1254 ensure!(1255 amount <= MAX_REFUNGIBLE_PIECES,1256 <Error<T>>::WrongRefungiblePieces1257 );1258 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1259 1260 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1261 let balance = <Balance<T>>::get((collection.id, token, owner));1262 ensure!(1263 total_pieces == balance,1264 <Error<T>>::RepartitionWhileNotOwningAllPieces1265 );12661267 <Balance<T>>::insert((collection.id, token, owner), amount);1268 <TotalSupply<T>>::insert((collection.id, token), amount);12691270 if amount > total_pieces {1271 let mint_amount = amount - total_pieces;1272 <PalletEvm<T>>::deposit_log(1273 ERC20Events::Transfer {1274 from: H160::default(),1275 to: *owner.as_eth(),1276 value: mint_amount.into(),1277 }1278 .to_log(T::EvmTokenAddressMapping::token_to_address(1279 collection.id,1280 token,1281 )),1282 );1283 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1284 collection.id,1285 token,1286 owner.clone(),1287 mint_amount,1288 ));1289 } else if total_pieces > amount {1290 let burn_amount = total_pieces - amount;1291 <PalletEvm<T>>::deposit_log(1292 ERC20Events::Transfer {1293 from: *owner.as_eth(),1294 to: H160::default(),1295 value: burn_amount.into(),1296 }1297 .to_log(T::EvmTokenAddressMapping::token_to_address(1298 collection.id,1299 token,1300 )),1301 );1302 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1303 collection.id,1304 token,1305 owner.clone(),1306 burn_amount,1307 ));1308 }13091310 Ok(())1311 }13121313 fn token_owner(1314 collection_id: CollectionId,1315 token_id: TokenId,1316 ) -> Result<T::CrossAccountId, TokenOwnerError> {1317 let mut owner = None;1318 let mut count = 0;1319 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1320 count += 1;1321 if count > 1 {1322 return Err(TokenOwnerError::MultipleOwners);1323 }1324 owner = Some(key);1325 }1326 owner.ok_or(TokenOwnerError::NotFound)1327 }13281329 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1330 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1331 }13321333 pub fn set_collection_properties(1334 collection: &RefungibleHandle<T>,1335 sender: &T::CrossAccountId,1336 properties: Vec<Property>,1337 ) -> DispatchResult {1338 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())1339 }13401341 pub fn delete_collection_properties(1342 collection: &RefungibleHandle<T>,1343 sender: &T::CrossAccountId,1344 property_keys: Vec<PropertyKey>,1345 ) -> DispatchResult {1346 <PalletCommon<T>>::delete_collection_properties(1347 collection,1348 sender,1349 property_keys.into_iter(),1350 )1351 }13521353 pub fn set_token_property_permissions(1354 collection: &RefungibleHandle<T>,1355 sender: &T::CrossAccountId,1356 property_permissions: Vec<PropertyKeyPermission>,1357 ) -> DispatchResult {1358 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1359 }13601361 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1362 <PalletCommon<T>>::property_permissions(collection_id)1363 }13641365 pub fn set_scoped_token_property_permissions(1366 collection: &RefungibleHandle<T>,1367 sender: &T::CrossAccountId,1368 scope: PropertyScope,1369 property_permissions: Vec<PropertyKeyPermission>,1370 ) -> DispatchResult {1371 <PalletCommon<T>>::set_scoped_token_property_permissions(1372 collection,1373 sender,1374 scope,1375 property_permissions,1376 )1377 }13781379 1380 1381 1382 1383 1384 1385 pub fn token_owners(1386 collection_id: CollectionId,1387 token: TokenId,1388 ) -> Option<Vec<T::CrossAccountId>> {1389 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1390 .map(|(owner, _amount)| owner)1391 .take(10)1392 .collect();13931394 if res.is_empty() {1395 None1396 } else {1397 Some(res)1398 }1399 }14001401 1402 1403 1404 1405 1406 1407 pub fn set_allowance_for_all(1408 collection: &RefungibleHandle<T>,1409 owner: &T::CrossAccountId,1410 spender: &T::CrossAccountId,1411 approve: bool,1412 ) -> DispatchResult {1413 <PalletCommon<T>>::set_allowance_for_all(1414 collection,1415 owner,1416 spender,1417 approve,1418 || <CollectionAllowance<T>>::insert((collection.id, owner, spender), approve),1419 ERC721Events::ApprovalForAll {1420 owner: *owner.as_eth(),1421 operator: *spender.as_eth(),1422 approved: approve,1423 }1424 .to_log(collection_id_to_address(collection.id)),1425 )1426 }14271428 1429 pub fn allowance_for_all(1430 collection: &RefungibleHandle<T>,1431 owner: &T::CrossAccountId,1432 spender: &T::CrossAccountId,1433 ) -> bool {1434 <CollectionAllowance<T>>::get((collection.id, owner, spender))1435 }14361437 pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1438 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1439 properties.recompute_consumed_space();1440 });14411442 Ok(())1443 }1444}