12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788#![cfg_attr(not(feature = "std"), no_std)]8990use core::{cmp::Ordering, ops::Deref};9192use evm_coder::ToLog;93use frame_support::{ensure, storage::with_transaction, transactional};94pub use pallet::*;95use pallet_common::{96 eth::collection_id_to_address, Error as CommonError, Event as CommonEvent,97 Pallet as PalletCommon,98};99use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};100use pallet_evm_coder_substrate::WithRecorder;101use pallet_structure::Pallet as PalletStructure;102use sp_core::{Get, H160};103use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};104use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};105use up_data_structs::{106 budget::Budget, mapping::TokenAddressMapping, AccessMode, CollectionId,107 CreateRefungibleExMultipleOwners, PropertiesPermissionMap, Property, PropertyKey,108 PropertyKeyPermission, PropertyScope, PropertyValue, TokenId, TokenOwnerError,109 TokenProperties as TokenPropertiesT, MAX_REFUNGIBLE_PIECES,110};111112use crate::{erc::ERC721Events, erc_token::ERC20Events};113#[cfg(feature = "runtime-benchmarks")]114pub mod benchmarking;115pub mod common;116pub mod erc;117pub mod erc_token;118pub mod weights;119120pub type CreateItemData<T> =121 CreateRefungibleExMultipleOwners<<T as pallet_evm::Config>::CrossAccountId>;122pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;123124#[frame_support::pallet]125pub mod pallet {126 use frame_support::{127 pallet_prelude::*, storage::Key, traits::StorageVersion, Blake2_128, Blake2_128Concat,128 Twox64Concat,129 };130 use up_data_structs::{CollectionId, TokenId};131132 use super::{weights::WeightInfo, *};133134 #[pallet::error]135 pub enum Error<T> {136 137 NotRefungibleDataUsedToMintFungibleCollectionToken,138 139 WrongRefungiblePieces,140 141 RepartitionWhileNotOwningAllPieces,142 143 RefungibleDisallowsNesting,144 145 SettingPropertiesNotAllowed,146 }147148 #[pallet::config]149 pub trait Config:150 frame_system::Config + pallet_common::Config + pallet_structure::Config151 {152 type WeightInfo: WeightInfo;153 }154155 const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);156157 #[pallet::pallet]158 #[pallet::storage_version(STORAGE_VERSION)]159 pub struct Pallet<T>(_);160161 162 #[pallet::storage]163 pub type TokensMinted<T: Config> =164 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;165166 167 #[pallet::storage]168 pub type TokensBurnt<T: Config> =169 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;170171 172 #[pallet::storage]173 #[pallet::getter(fn token_properties)]174 pub type TokenProperties<T: Config> = StorageNMap<175 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),176 Value = TokenPropertiesT,177 QueryKind = OptionQuery,178 >;179180 181 #[pallet::storage]182 pub type TotalSupply<T: Config> = StorageNMap<183 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),184 Value = u128,185 QueryKind = ValueQuery,186 >;187188 189 #[pallet::storage]190 pub type Owned<T: Config> = StorageNMap<191 Key = (192 Key<Twox64Concat, CollectionId>,193 Key<Blake2_128Concat, T::CrossAccountId>,194 Key<Twox64Concat, TokenId>,195 ),196 Value = bool,197 QueryKind = ValueQuery,198 >;199200 201 #[pallet::storage]202 pub type AccountBalance<T: Config> = StorageNMap<203 Key = (204 Key<Twox64Concat, CollectionId>,205 206 Key<Blake2_128Concat, T::CrossAccountId>,207 ),208 Value = u32,209 QueryKind = ValueQuery,210 >;211212 213 #[pallet::storage]214 pub type Balance<T: Config> = StorageNMap<215 Key = (216 Key<Twox64Concat, CollectionId>,217 Key<Twox64Concat, TokenId>,218 219 Key<Blake2_128Concat, T::CrossAccountId>,220 ),221 Value = u128,222 QueryKind = ValueQuery,223 >;224225 226 #[pallet::storage]227 pub type Allowance<T: Config> = StorageNMap<228 Key = (229 Key<Twox64Concat, CollectionId>,230 Key<Twox64Concat, TokenId>,231 232 Key<Blake2_128, T::CrossAccountId>,233 234 Key<Blake2_128Concat, T::CrossAccountId>,235 ),236 Value = u128,237 QueryKind = ValueQuery,238 >;239240 241 #[pallet::storage]242 pub type CollectionAllowance<T: Config> = StorageNMap<243 Key = (244 Key<Twox64Concat, CollectionId>,245 Key<Blake2_128Concat, T::CrossAccountId>, 246 Key<Blake2_128Concat, T::CrossAccountId>, 247 ),248 Value = bool,249 QueryKind = ValueQuery,250 >;251}252253pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);254impl<T: Config> RefungibleHandle<T> {255 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {256 Self(inner)257 }258 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {259 self.0260 }261 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {262 &mut self.0263 }264}265266impl<T: Config> Deref for RefungibleHandle<T> {267 type Target = pallet_common::CollectionHandle<T>;268269 fn deref(&self) -> &Self::Target {270 &self.0271 }272}273274impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {275 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {276 self.0.recorder()277 }278 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {279 self.0.into_recorder()280 }281}282283impl<T: Config> Pallet<T> {284 285 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {286 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)287 }288289 290 291 292 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {293 <TotalSupply<T>>::contains_key((collection.id, token))294 }295}296297298impl<T: Config> Pallet<T> {299 300 301 302 303 pub fn destroy_collection(304 collection: RefungibleHandle<T>,305 sender: &T::CrossAccountId,306 ) -> DispatchResult {307 let id = collection.id;308309 if Self::collection_has_tokens(id) {310 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());311 }312313 314315 PalletCommon::destroy_collection(collection.0, sender)?;316317 <TokensMinted<T>>::remove(id);318 <TokensBurnt<T>>::remove(id);319 let _ = <TotalSupply<T>>::clear_prefix((id,), u32::MAX, None);320 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);321 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);322 let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);323 let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);324 Ok(())325 }326327 fn collection_has_tokens(collection_id: CollectionId) -> bool {328 <TotalSupply<T>>::iter_prefix((collection_id,))329 .next()330 .is_some()331 }332333 pub fn burn_token_unchecked(334 collection: &RefungibleHandle<T>,335 owner: &T::CrossAccountId,336 token_id: TokenId,337 ) -> DispatchResult {338 let burnt = <TokensBurnt<T>>::get(collection.id)339 .checked_add(1)340 .ok_or(ArithmeticError::Overflow)?;341342 <TokensBurnt<T>>::insert(collection.id, burnt);343 <TokenProperties<T>>::remove((collection.id, token_id));344 <TotalSupply<T>>::remove((collection.id, token_id));345 let _ = <Balance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);346 let _ = <Allowance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);347 <PalletEvm<T>>::deposit_log(348 ERC721Events::Transfer {349 from: *owner.as_eth(),350 to: H160::default(),351 token_id: token_id.into(),352 }353 .to_log(collection_id_to_address(collection.id)),354 );355 Ok(())356 }357358 359 360 361 362 363 364 365 366 367 368 369 pub fn burn(370 collection: &RefungibleHandle<T>,371 owner: &T::CrossAccountId,372 token: TokenId,373 amount: u128,374 ) -> DispatchResult {375 if <Balance<T>>::get((collection.id, token, owner)) == 0 {376 return Err(<CommonError<T>>::TokenValueTooLow.into());377 }378379 let total_supply = <TotalSupply<T>>::get((collection.id, token))380 .checked_sub(amount)381 .ok_or(<CommonError<T>>::TokenValueTooLow)?;382383 384 if total_supply == 0 {385 386 ensure!(387 <Balance<T>>::get((collection.id, token, owner)) == amount,388 <CommonError<T>>::TokenValueTooLow389 );390 let account_balance = <AccountBalance<T>>::get((collection.id, owner))391 .checked_sub(1)392 393 .ok_or(ArithmeticError::Underflow)?;394395 396397 <Owned<T>>::remove((collection.id, owner, token));398 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);399 <AccountBalance<T>>::insert((collection.id, owner), account_balance);400 Self::burn_token_unchecked(collection, owner, token)?;401 <PalletEvm<T>>::deposit_log(402 ERC20Events::Transfer {403 from: *owner.as_eth(),404 to: H160::default(),405 value: amount.into(),406 }407 .to_log(collection_id_to_address(collection.id)),408 );409 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(410 collection.id,411 token,412 owner.clone(),413 amount,414 ));415 return Ok(());416 }417418 let balance = <Balance<T>>::get((collection.id, token, owner))419 .checked_sub(amount)420 .ok_or(<CommonError<T>>::TokenValueTooLow)?;421 let account_balance = if balance == 0 {422 <AccountBalance<T>>::get((collection.id, owner))423 .checked_sub(1)424 425 .ok_or(ArithmeticError::Underflow)?426 } else {427 0428 };429430 431432 if balance == 0 {433 <Owned<T>>::remove((collection.id, owner, token));434 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);435 <Balance<T>>::remove((collection.id, token, owner));436 <AccountBalance<T>>::insert((collection.id, owner), account_balance);437438 if let Ok(user) = Self::token_owner(collection.id, token) {439 <PalletEvm<T>>::deposit_log(440 ERC721Events::Transfer {441 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,442 to: *user.as_eth(),443 token_id: token.into(),444 }445 .to_log(collection_id_to_address(collection.id)),446 );447 }448 } else {449 <Balance<T>>::insert((collection.id, token, owner), balance);450 }451 <TotalSupply<T>>::insert((collection.id, token), total_supply);452453 <PalletEvm<T>>::deposit_log(454 ERC20Events::Transfer {455 from: *owner.as_eth(),456 to: H160::default(),457 value: amount.into(),458 }459 .to_log(T::EvmTokenAddressMapping::token_to_address(460 collection.id,461 token,462 )),463 );464 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(465 collection.id,466 token,467 owner.clone(),468 amount,469 ));470 Ok(())471 }472473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 #[transactional]489 fn modify_token_properties(490 collection: &RefungibleHandle<T>,491 sender: &T::CrossAccountId,492 token_id: TokenId,493 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,494 nesting_budget: &dyn Budget,495 ) -> DispatchResult {496 let mut property_writer =497 pallet_common::ExistingTokenPropertyWriter::new(collection, sender);498499 property_writer.write_token_properties(500 sender,501 token_id,502 properties_updates,503 nesting_budget,504 erc::ERC721TokenEvent::TokenChanged {505 token_id: token_id.into(),506 }507 .to_log(T::ContractAddress::get()),508 )509 }510511 pub fn next_token_id(collection: &RefungibleHandle<T>) -> Result<TokenId, DispatchError> {512 let next_token_id = <TokensMinted<T>>::get(collection.id)513 .checked_add(1)514 .ok_or(<CommonError<T>>::CollectionTokenLimitExceeded)?;515516 ensure!(517 collection.limits.token_limit() >= next_token_id,518 <CommonError<T>>::CollectionTokenLimitExceeded519 );520521 Ok(TokenId(next_token_id))522 }523524 pub fn set_token_properties(525 collection: &RefungibleHandle<T>,526 sender: &T::CrossAccountId,527 token_id: TokenId,528 properties: impl Iterator<Item = Property>,529 nesting_budget: &dyn Budget,530 ) -> DispatchResult {531 Self::modify_token_properties(532 collection,533 sender,534 token_id,535 properties.map(|p| (p.key, Some(p.value))),536 nesting_budget,537 )538 }539540 pub fn set_token_property(541 collection: &RefungibleHandle<T>,542 sender: &T::CrossAccountId,543 token_id: TokenId,544 property: Property,545 nesting_budget: &dyn Budget,546 ) -> DispatchResult {547 Self::set_token_properties(548 collection,549 sender,550 token_id,551 [property].into_iter(),552 nesting_budget,553 )554 }555556 pub fn delete_token_properties(557 collection: &RefungibleHandle<T>,558 sender: &T::CrossAccountId,559 token_id: TokenId,560 property_keys: impl Iterator<Item = PropertyKey>,561 nesting_budget: &dyn Budget,562 ) -> DispatchResult {563 Self::modify_token_properties(564 collection,565 sender,566 token_id,567 property_keys.into_iter().map(|key| (key, None)),568 nesting_budget,569 )570 }571572 pub fn delete_token_property(573 collection: &RefungibleHandle<T>,574 sender: &T::CrossAccountId,575 token_id: TokenId,576 property_key: PropertyKey,577 nesting_budget: &dyn Budget,578 ) -> DispatchResult {579 Self::delete_token_properties(580 collection,581 sender,582 token_id,583 [property_key].into_iter(),584 nesting_budget,585 )586 }587588 589 590 591 592 593 594 595 596 597 pub fn transfer(598 collection: &RefungibleHandle<T>,599 from: &T::CrossAccountId,600 to: &T::CrossAccountId,601 token: TokenId,602 amount: u128,603 nesting_budget: &dyn Budget,604 ) -> DispatchResult {605 let depositor = from;606 Self::transfer_internal(607 collection,608 depositor,609 from,610 to,611 token,612 amount,613 nesting_budget,614 )615 }616617 618 619 620 pub fn transfer_internal(621 collection: &RefungibleHandle<T>,622 depositor: &T::CrossAccountId,623 from: &T::CrossAccountId,624 to: &T::CrossAccountId,625 token: TokenId,626 amount: u128,627 nesting_budget: &dyn Budget,628 ) -> DispatchResult {629 ensure!(630 collection.limits.transfers_enabled(),631 <CommonError<T>>::TransferNotAllowed632 );633634 if collection.permissions.access() == AccessMode::AllowList {635 collection.check_allowlist(from)?;636 collection.check_allowlist(to)?;637 }638 <PalletCommon<T>>::ensure_correct_receiver(to)?;639640 let initial_balance_from = <Balance<T>>::get((collection.id, token, from));641642 if initial_balance_from == 0 {643 return Err(<CommonError<T>>::TokenValueTooLow.into());644 }645646 let updated_balance_from = initial_balance_from647 .checked_sub(amount)648 .ok_or(<CommonError<T>>::TokenValueTooLow)?;649 let mut create_target = false;650 let from_to_differ = from != to;651 let updated_balance_to = if from != to && amount != 0 {652 let old_balance = <Balance<T>>::get((collection.id, token, to));653 if old_balance == 0 {654 create_target = true;655 }656 Some(657 old_balance658 .checked_add(amount)659 .ok_or(ArithmeticError::Overflow)?,660 )661 } else {662 None663 };664665 let account_balance_from = if updated_balance_from == 0 {666 Some(667 <AccountBalance<T>>::get((collection.id, from))668 .checked_sub(1)669 670 .ok_or(ArithmeticError::Underflow)?,671 )672 } else {673 None674 };675 676 677 let account_balance_to = if create_target && from_to_differ {678 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))679 .checked_add(1)680 .ok_or(ArithmeticError::Overflow)?;681 ensure!(682 account_balance_to < collection.limits.account_token_ownership_limit(),683 <CommonError<T>>::AccountTokenLimitExceeded,684 );685686 Some(account_balance_to)687 } else {688 None689 };690691 692693 if let Some(updated_balance_to) = updated_balance_to {694 695696 <PalletStructure<T>>::nest_if_sent_to_token(697 depositor,698 to,699 collection.id,700 token,701 nesting_budget,702 )?;703704 if updated_balance_from == 0 {705 <Balance<T>>::remove((collection.id, token, from));706 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);707 } else {708 <Balance<T>>::insert((collection.id, token, from), updated_balance_from);709 }710 <Balance<T>>::insert((collection.id, token, to), updated_balance_to);711 if let Some(account_balance_from) = account_balance_from {712 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);713 <Owned<T>>::remove((collection.id, from, token));714 }715 if let Some(account_balance_to) = account_balance_to {716 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);717 <Owned<T>>::insert((collection.id, to, token), true);718 }719 }720721 <PalletEvm<T>>::deposit_log(722 ERC20Events::Transfer {723 from: *from.as_eth(),724 to: *to.as_eth(),725 value: amount.into(),726 }727 .to_log(T::EvmTokenAddressMapping::token_to_address(728 collection.id,729 token,730 )),731 );732733 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(734 collection.id,735 token,736 from.clone(),737 to.clone(),738 amount,739 ));740741 let total_supply = <TotalSupply<T>>::get((collection.id, token));742743 if amount == total_supply {744 745 <PalletEvm<T>>::deposit_log(746 ERC721Events::Transfer {747 from: *from.as_eth(),748 to: *to.as_eth(),749 token_id: token.into(),750 }751 .to_log(collection_id_to_address(collection.id)),752 );753 } else if let Some(updated_balance_to) = updated_balance_to {754 755 756 if initial_balance_from == total_supply {757 758 759 <PalletEvm<T>>::deposit_log(760 ERC721Events::Transfer {761 from: *from.as_eth(),762 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,763 token_id: token.into(),764 }765 .to_log(collection_id_to_address(collection.id)),766 );767 } else if updated_balance_to == total_supply {768 769 <PalletEvm<T>>::deposit_log(770 ERC721Events::Transfer {771 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,772 to: *to.as_eth(),773 token_id: token.into(),774 }775 .to_log(collection_id_to_address(collection.id)),776 );777 }778 }779780 Ok(())781 }782783 784 785 786 787 788 pub fn create_multiple_items(789 collection: &RefungibleHandle<T>,790 sender: &T::CrossAccountId,791 data: Vec<CreateItemData<T>>,792 nesting_budget: &dyn Budget,793 ) -> DispatchResult {794 if !collection.is_owner_or_admin(sender) {795 ensure!(796 collection.permissions.mint_mode(),797 <CommonError<T>>::PublicMintingNotAllowed798 );799 collection.check_allowlist(sender)?;800801 for item in data.iter() {802 for user in item.users.keys() {803 collection.check_allowlist(user)?;804 }805 }806 }807808 for item in data.iter() {809 for (owner, _) in item.users.iter() {810 <PalletCommon<T>>::ensure_correct_receiver(owner)?;811 }812 }813814 815 let totals = data816 .iter()817 .map(|data| {818 Ok(data819 .users820 .iter()821 .map(|u| u.1)822 .try_fold(0u128, |acc, v| acc.checked_add(*v))823 .ok_or(ArithmeticError::Overflow)?)824 })825 .collect::<Result<Vec<_>, DispatchError>>()?;826 for total in &totals {827 ensure!(828 *total <= MAX_REFUNGIBLE_PIECES,829 <Error<T>>::WrongRefungiblePieces830 );831 }832833 let first_token_id = <TokensMinted<T>>::get(collection.id);834 let tokens_minted = first_token_id835 .checked_add(data.len() as u32)836 .ok_or(ArithmeticError::Overflow)?;837 ensure!(838 tokens_minted < collection.limits.token_limit(),839 <CommonError<T>>::CollectionTokenLimitExceeded840 );841842 let mut balances = BTreeMap::new();843 for data in &data {844 for owner in data.users.keys() {845 let balance = balances846 .entry(owner)847 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));848 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;849850 ensure!(851 *balance <= collection.limits.account_token_ownership_limit(),852 <CommonError<T>>::AccountTokenLimitExceeded,853 );854 }855 }856857 for (i, token) in data.iter().enumerate() {858 let token_id = TokenId(first_token_id + i as u32 + 1);859 for (to, _) in token.users.iter() {860 <PalletStructure<T>>::check_nesting(861 sender,862 to,863 collection.id,864 token_id,865 nesting_budget,866 )?;867 }868 }869870 871872 let mut property_writer = pallet_common::NewTokenPropertyWriter::new(collection, sender);873874 with_transaction(|| {875 for (i, data) in data.iter().enumerate() {876 let token_id = first_token_id + i as u32 + 1;877 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);878879 let token = TokenId(token_id);880881 let mut mint_target_is_sender = true;882 for (user, amount) in data.users.iter() {883 if *amount == 0 {884 continue;885 }886887 mint_target_is_sender = mint_target_is_sender && sender.conv_eq(user);888889 <Balance<T>>::insert((collection.id, token_id, &user), amount);890 <Owned<T>>::insert((collection.id, &user, token), true);891 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(892 user,893 collection.id,894 token,895 );896 }897898 if let Err(e) = property_writer.write_token_properties(899 mint_target_is_sender,900 token,901 data.properties.clone().into_iter(),902 erc::ERC721TokenEvent::TokenChanged {903 token_id: token.into(),904 }905 .to_log(T::ContractAddress::get()),906 ) {907 return TransactionOutcome::Rollback(Err(e));908 }909 }910 TransactionOutcome::Commit(Ok(()))911 })?;912913 <TokensMinted<T>>::insert(collection.id, tokens_minted);914915 for (account, balance) in balances {916 <AccountBalance<T>>::insert((collection.id, account), balance);917 }918919 for (i, token) in data.into_iter().enumerate() {920 let token_id = first_token_id + i as u32 + 1;921922 let receivers = token923 .users924 .into_iter()925 .filter(|(_, amount)| *amount > 0)926 .collect::<Vec<_>>();927928 if let [(user, _)] = receivers.as_slice() {929 930 <PalletEvm<T>>::deposit_log(931 ERC721Events::Transfer {932 from: H160::default(),933 to: *user.as_eth(),934 token_id: token_id.into(),935 }936 .to_log(collection_id_to_address(collection.id)),937 );938 } else if let [_, ..] = receivers.as_slice() {939 940 <PalletEvm<T>>::deposit_log(941 ERC721Events::Transfer {942 from: H160::default(),943 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,944 token_id: token_id.into(),945 }946 .to_log(collection_id_to_address(collection.id)),947 );948 }949950 for (user, amount) in receivers.into_iter() {951 <PalletEvm<T>>::deposit_log(952 ERC20Events::Transfer {953 from: H160::default(),954 to: *user.as_eth(),955 value: amount.into(),956 }957 .to_log(T::EvmTokenAddressMapping::token_to_address(958 collection.id,959 TokenId(token_id),960 )),961 );962 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(963 collection.id,964 TokenId(token_id),965 user,966 amount,967 ));968 }969 }970 Ok(())971 }972973 pub fn set_allowance_unchecked(974 collection: &RefungibleHandle<T>,975 sender: &T::CrossAccountId,976 spender: &T::CrossAccountId,977 token: TokenId,978 amount: u128,979 ) {980 if amount == 0 {981 <Allowance<T>>::remove((collection.id, token, sender, spender));982 } else {983 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);984 }985986 <PalletEvm<T>>::deposit_log(987 ERC20Events::Approval {988 owner: *sender.as_eth(),989 spender: *spender.as_eth(),990 value: amount.into(),991 }992 .to_log(T::EvmTokenAddressMapping::token_to_address(993 collection.id,994 token,995 )),996 );997 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(998 collection.id,999 token,1000 sender.clone(),1001 spender.clone(),1002 amount,1003 ))1004 }10051006 1007 1008 1009 pub fn set_allowance(1010 collection: &RefungibleHandle<T>,1011 sender: &T::CrossAccountId,1012 spender: &T::CrossAccountId,1013 token: TokenId,1014 amount: u128,1015 ) -> DispatchResult {1016 if collection.permissions.access() == AccessMode::AllowList {1017 collection.check_allowlist(sender)?;1018 collection.check_allowlist(spender)?;1019 }10201021 <PalletCommon<T>>::ensure_correct_receiver(spender)?;10221023 if <Balance<T>>::get((collection.id, token, sender)) < amount {1024 ensure!(1025 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1026 <CommonError<T>>::CantApproveMoreThanOwned1027 );1028 }10291030 10311032 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1033 Ok(())1034 }10351036 1037 1038 1039 1040 1041 pub fn set_allowance_from(1042 collection: &RefungibleHandle<T>,1043 sender: &T::CrossAccountId,1044 from: &T::CrossAccountId,1045 to: &T::CrossAccountId,1046 token_id: TokenId,1047 amount: u128,1048 ) -> DispatchResult {1049 if collection.permissions.access() == AccessMode::AllowList {1050 collection.check_allowlist(sender)?;1051 collection.check_allowlist(from)?;1052 collection.check_allowlist(to)?;1053 }10541055 <PalletCommon<T>>::ensure_correct_receiver(to)?;10561057 ensure!(1058 sender.conv_eq(from),1059 <CommonError<T>>::AddressIsNotEthMirror1060 );10611062 if <Balance<T>>::get((collection.id, token_id, from)) < amount {1063 ensure!(1064 collection.limits.owner_can_transfer()1065 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1066 && Self::token_exists(collection, token_id),1067 <CommonError<T>>::CantApproveMoreThanOwned1068 );1069 }10701071 10721073 Self::set_allowance_unchecked(collection, from, to, token_id, amount);1074 Ok(())1075 }10761077 1078 fn check_allowed(1079 collection: &RefungibleHandle<T>,1080 spender: &T::CrossAccountId,1081 from: &T::CrossAccountId,1082 token: TokenId,1083 amount: u128,1084 nesting_budget: &dyn Budget,1085 ) -> Result<Option<u128>, DispatchError> {1086 if spender.conv_eq(from) {1087 return Ok(None);1088 }1089 if collection.permissions.access() == AccessMode::AllowList {1090 1091 collection.check_allowlist(spender)?;1092 }10931094 if collection.ignores_token_restrictions(spender) {1095 return Ok(Self::compute_allowance_decrease(1096 collection, token, from, spender, amount,1097 ));1098 }10991100 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1101 1102 ensure!(1103 <PalletStructure<T>>::check_indirectly_owned(1104 spender.clone(),1105 source.0,1106 source.1,1107 None,1108 nesting_budget1109 )?,1110 <CommonError<T>>::ApprovedValueTooLow,1111 );1112 return Ok(None);1113 }11141115 let allowance = Self::compute_allowance_decrease(collection, token, from, spender, amount);1116 if allowance.is_some() {1117 return Ok(allowance);1118 }11191120 1121 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1122 return Ok(allowance);1123 }11241125 Err(<CommonError<T>>::ApprovedValueTooLow.into())1126 }11271128 1129 1130 fn compute_allowance_decrease(1131 collection: &RefungibleHandle<T>,1132 token: TokenId,1133 from: &T::CrossAccountId,1134 spender: &T::CrossAccountId,1135 amount: u128,1136 ) -> Option<u128> {1137 <Allowance<T>>::get((collection.id, token, from, spender)).checked_sub(amount)1138 }11391140 1141 1142 1143 1144 1145 1146 pub fn transfer_from(1147 collection: &RefungibleHandle<T>,1148 spender: &T::CrossAccountId,1149 from: &T::CrossAccountId,1150 to: &T::CrossAccountId,1151 token: TokenId,1152 amount: u128,1153 nesting_budget: &dyn Budget,1154 ) -> DispatchResult {1155 let allowance =1156 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11571158 11591160 Self::transfer_internal(collection, spender, from, to, token, amount, nesting_budget)?;1161 if let Some(allowance) = allowance {1162 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1163 }1164 Ok(())1165 }11661167 1168 1169 1170 1171 1172 1173 pub fn burn_from(1174 collection: &RefungibleHandle<T>,1175 spender: &T::CrossAccountId,1176 from: &T::CrossAccountId,1177 token: TokenId,1178 amount: u128,1179 nesting_budget: &dyn Budget,1180 ) -> DispatchResult {1181 let allowance =1182 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11831184 11851186 Self::burn(collection, from, token, amount)?;1187 if let Some(allowance) = allowance {1188 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1189 }1190 Ok(())1191 }11921193 1194 1195 1196 1197 1198 1199 1200 pub fn create_item(1201 collection: &RefungibleHandle<T>,1202 sender: &T::CrossAccountId,1203 data: CreateItemData<T>,1204 nesting_budget: &dyn Budget,1205 ) -> DispatchResult {1206 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1207 }12081209 1210 1211 1212 1213 1214 1215 1216 pub fn repartition(1217 collection: &RefungibleHandle<T>,1218 owner: &T::CrossAccountId,1219 token: TokenId,1220 amount: u128,1221 ) -> DispatchResult {1222 ensure!(1223 amount <= MAX_REFUNGIBLE_PIECES,1224 <Error<T>>::WrongRefungiblePieces1225 );1226 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1227 1228 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1229 let balance = <Balance<T>>::get((collection.id, token, owner));1230 ensure!(1231 total_pieces == balance,1232 <Error<T>>::RepartitionWhileNotOwningAllPieces1233 );12341235 <Balance<T>>::insert((collection.id, token, owner), amount);1236 <TotalSupply<T>>::insert((collection.id, token), amount);12371238 match total_pieces.cmp(&amount) {1239 Ordering::Less => {1240 let mint_amount = amount - total_pieces;1241 <PalletEvm<T>>::deposit_log(1242 ERC20Events::Transfer {1243 from: H160::default(),1244 to: *owner.as_eth(),1245 value: mint_amount.into(),1246 }1247 .to_log(T::EvmTokenAddressMapping::token_to_address(1248 collection.id,1249 token,1250 )),1251 );1252 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1253 collection.id,1254 token,1255 owner.clone(),1256 mint_amount,1257 ));1258 }1259 Ordering::Greater => {1260 let burn_amount = total_pieces - amount;1261 <PalletEvm<T>>::deposit_log(1262 ERC20Events::Transfer {1263 from: *owner.as_eth(),1264 to: H160::default(),1265 value: burn_amount.into(),1266 }1267 .to_log(T::EvmTokenAddressMapping::token_to_address(1268 collection.id,1269 token,1270 )),1271 );1272 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1273 collection.id,1274 token,1275 owner.clone(),1276 burn_amount,1277 ));1278 }1279 Ordering::Equal => {}1280 }12811282 Ok(())1283 }12841285 fn token_owner(1286 collection_id: CollectionId,1287 token_id: TokenId,1288 ) -> Result<T::CrossAccountId, TokenOwnerError> {1289 let mut owner = None;1290 let mut count = 0;1291 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1292 count += 1;1293 if count > 1 {1294 return Err(TokenOwnerError::MultipleOwners);1295 }1296 owner = Some(key);1297 }1298 owner.ok_or(TokenOwnerError::NotFound)1299 }13001301 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1302 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1303 }13041305 pub fn set_collection_properties(1306 collection: &RefungibleHandle<T>,1307 sender: &T::CrossAccountId,1308 properties: Vec<Property>,1309 ) -> DispatchResult {1310 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())1311 }13121313 pub fn delete_collection_properties(1314 collection: &RefungibleHandle<T>,1315 sender: &T::CrossAccountId,1316 property_keys: Vec<PropertyKey>,1317 ) -> DispatchResult {1318 <PalletCommon<T>>::delete_collection_properties(1319 collection,1320 sender,1321 property_keys.into_iter(),1322 )1323 }13241325 pub fn set_token_property_permissions(1326 collection: &RefungibleHandle<T>,1327 sender: &T::CrossAccountId,1328 property_permissions: Vec<PropertyKeyPermission>,1329 ) -> DispatchResult {1330 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1331 }13321333 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1334 <PalletCommon<T>>::property_permissions(collection_id)1335 }13361337 pub fn set_scoped_token_property_permissions(1338 collection: &RefungibleHandle<T>,1339 sender: &T::CrossAccountId,1340 scope: PropertyScope,1341 property_permissions: Vec<PropertyKeyPermission>,1342 ) -> DispatchResult {1343 <PalletCommon<T>>::set_scoped_token_property_permissions(1344 collection,1345 sender,1346 scope,1347 property_permissions,1348 )1349 }13501351 1352 1353 1354 1355 1356 1357 pub fn token_owners(1358 collection_id: CollectionId,1359 token: TokenId,1360 ) -> Option<Vec<T::CrossAccountId>> {1361 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1362 .map(|(owner, _amount)| owner)1363 .take(10)1364 .collect();13651366 if res.is_empty() {1367 None1368 } else {1369 Some(res)1370 }1371 }13721373 1374 1375 1376 1377 1378 1379 pub fn set_allowance_for_all(1380 collection: &RefungibleHandle<T>,1381 owner: &T::CrossAccountId,1382 spender: &T::CrossAccountId,1383 approve: bool,1384 ) -> DispatchResult {1385 <PalletCommon<T>>::set_allowance_for_all(1386 collection,1387 owner,1388 spender,1389 approve,1390 || <CollectionAllowance<T>>::insert((collection.id, owner, spender), approve),1391 ERC721Events::ApprovalForAll {1392 owner: *owner.as_eth(),1393 operator: *spender.as_eth(),1394 approved: approve,1395 }1396 .to_log(collection_id_to_address(collection.id)),1397 )1398 }13991400 1401 pub fn allowance_for_all(1402 collection: &RefungibleHandle<T>,1403 owner: &T::CrossAccountId,1404 spender: &T::CrossAccountId,1405 ) -> bool {1406 <CollectionAllowance<T>>::get((collection.id, owner, spender))1407 }14081409 pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1410 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1411 if let Some(properties) = properties {1412 properties.recompute_consumed_space();1413 }1414 });14151416 Ok(())1417 }1418}