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};112113pub use pallet::*;114#[cfg(feature = "runtime-benchmarks")]115pub mod benchmarking;116pub mod common;117pub mod erc;118pub mod erc_token;119pub mod weights;120121pub type CreateItemData<T> =122 CreateRefungibleExMultipleOwners<<T as pallet_evm::Config>::CrossAccountId>;123pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;124125#[frame_support::pallet]126pub mod pallet {127 use super::*;128 use frame_support::{129 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,130 traits::StorageVersion,131 };132 use up_data_structs::{CollectionId, TokenId};133 use super::weights::WeightInfo;134135 #[pallet::error]136 pub enum Error<T> {137 138 NotRefungibleDataUsedToMintFungibleCollectionToken,139 140 WrongRefungiblePieces,141 142 RepartitionWhileNotOwningAllPieces,143 144 RefungibleDisallowsNesting,145 146 SettingPropertiesNotAllowed,147 }148149 #[pallet::config]150 pub trait Config:151 frame_system::Config + pallet_common::Config + pallet_structure::Config152 {153 type WeightInfo: WeightInfo;154 }155156 const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);157158 #[pallet::pallet]159 #[pallet::storage_version(STORAGE_VERSION)]160 #[pallet::generate_store(pub(super) trait Store)]161 pub struct Pallet<T>(_);162163 164 #[pallet::storage]165 pub type TokensMinted<T: Config> =166 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;167168 169 #[pallet::storage]170 pub type TokensBurnt<T: Config> =171 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;172173 174 #[pallet::storage]175 #[pallet::getter(fn token_properties)]176 pub type TokenProperties<T: Config> = StorageNMap<177 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),178 Value = up_data_structs::Properties,179 QueryKind = ValueQuery,180 OnEmpty = up_data_structs::TokenProperties,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 collection_id: collection_id_to_address(collection.id),576 token_id: token_id.into(),577 }578 .to_log(T::ContractAddress::get()),579 )580 }581582 pub fn set_token_properties(583 collection: &RefungibleHandle<T>,584 sender: &T::CrossAccountId,585 token_id: TokenId,586 properties: impl Iterator<Item = Property>,587 is_token_create: bool,588 nesting_budget: &dyn Budget,589 ) -> DispatchResult {590 Self::modify_token_properties(591 collection,592 sender,593 token_id,594 properties.map(|p| (p.key, Some(p.value))),595 is_token_create,596 nesting_budget,597 )598 }599600 pub fn set_token_property(601 collection: &RefungibleHandle<T>,602 sender: &T::CrossAccountId,603 token_id: TokenId,604 property: Property,605 nesting_budget: &dyn Budget,606 ) -> DispatchResult {607 let is_token_create = false;608609 Self::set_token_properties(610 collection,611 sender,612 token_id,613 [property].into_iter(),614 is_token_create,615 nesting_budget,616 )617 }618619 pub fn delete_token_properties(620 collection: &RefungibleHandle<T>,621 sender: &T::CrossAccountId,622 token_id: TokenId,623 property_keys: impl Iterator<Item = PropertyKey>,624 nesting_budget: &dyn Budget,625 ) -> DispatchResult {626 let is_token_create = false;627628 Self::modify_token_properties(629 collection,630 sender,631 token_id,632 property_keys.into_iter().map(|key| (key, None)),633 is_token_create,634 nesting_budget,635 )636 }637638 pub fn delete_token_property(639 collection: &RefungibleHandle<T>,640 sender: &T::CrossAccountId,641 token_id: TokenId,642 property_key: PropertyKey,643 nesting_budget: &dyn Budget,644 ) -> DispatchResult {645 Self::delete_token_properties(646 collection,647 sender,648 token_id,649 [property_key].into_iter(),650 nesting_budget,651 )652 }653654 655 656 657 658 659 660 661 662 663 pub fn transfer(664 collection: &RefungibleHandle<T>,665 from: &T::CrossAccountId,666 to: &T::CrossAccountId,667 token: TokenId,668 amount: u128,669 nesting_budget: &dyn Budget,670 ) -> DispatchResult {671 ensure!(672 collection.limits.transfers_enabled(),673 <CommonError<T>>::TransferNotAllowed674 );675676 if collection.permissions.access() == AccessMode::AllowList {677 collection.check_allowlist(from)?;678 collection.check_allowlist(to)?;679 }680 <PalletCommon<T>>::ensure_correct_receiver(to)?;681682 let initial_balance_from = <Balance<T>>::get((collection.id, token, from));683684 if initial_balance_from == 0 {685 return Err(<CommonError<T>>::TokenValueTooLow.into());686 }687688 let updated_balance_from = initial_balance_from689 .checked_sub(amount)690 .ok_or(<CommonError<T>>::TokenValueTooLow)?;691 let mut create_target = false;692 let from_to_differ = from != to;693 let updated_balance_to = if from != to && amount != 0 {694 let old_balance = <Balance<T>>::get((collection.id, token, to));695 if old_balance == 0 {696 create_target = true;697 }698 Some(699 old_balance700 .checked_add(amount)701 .ok_or(ArithmeticError::Overflow)?,702 )703 } else {704 None705 };706707 let account_balance_from = if updated_balance_from == 0 {708 Some(709 <AccountBalance<T>>::get((collection.id, from))710 .checked_sub(1)711 712 .ok_or(ArithmeticError::Underflow)?,713 )714 } else {715 None716 };717 718 719 let account_balance_to = if create_target && from_to_differ {720 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))721 .checked_add(1)722 .ok_or(ArithmeticError::Overflow)?;723 ensure!(724 account_balance_to < collection.limits.account_token_ownership_limit(),725 <CommonError<T>>::AccountTokenLimitExceeded,726 );727728 Some(account_balance_to)729 } else {730 None731 };732733 734735 if let Some(updated_balance_to) = updated_balance_to {736 737738 <PalletStructure<T>>::nest_if_sent_to_token(739 from.clone(),740 to,741 collection.id,742 token,743 nesting_budget,744 )?;745746 if updated_balance_from == 0 {747 <Balance<T>>::remove((collection.id, token, from));748 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);749 } else {750 <Balance<T>>::insert((collection.id, token, from), updated_balance_from);751 }752 <Balance<T>>::insert((collection.id, token, to), updated_balance_to);753 if let Some(account_balance_from) = account_balance_from {754 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);755 <Owned<T>>::remove((collection.id, from, token));756 }757 if let Some(account_balance_to) = account_balance_to {758 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);759 <Owned<T>>::insert((collection.id, to, token), true);760 }761 }762763 <PalletEvm<T>>::deposit_log(764 ERC20Events::Transfer {765 from: *from.as_eth(),766 to: *to.as_eth(),767 value: amount.into(),768 }769 .to_log(T::EvmTokenAddressMapping::token_to_address(770 collection.id,771 token,772 )),773 );774775 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(776 collection.id,777 token,778 from.clone(),779 to.clone(),780 amount,781 ));782783 let total_supply = <TotalSupply<T>>::get((collection.id, token));784785 if amount == total_supply {786 787 <PalletEvm<T>>::deposit_log(788 ERC721Events::Transfer {789 from: *from.as_eth(),790 to: *to.as_eth(),791 token_id: token.into(),792 }793 .to_log(collection_id_to_address(collection.id)),794 );795 } else if let Some(updated_balance_to) = updated_balance_to {796 797 798 if initial_balance_from == total_supply {799 800 801 <PalletEvm<T>>::deposit_log(802 ERC721Events::Transfer {803 from: *from.as_eth(),804 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,805 token_id: token.into(),806 }807 .to_log(collection_id_to_address(collection.id)),808 );809 } else if updated_balance_to == total_supply {810 811 <PalletEvm<T>>::deposit_log(812 ERC721Events::Transfer {813 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,814 to: *to.as_eth(),815 token_id: token.into(),816 }817 .to_log(collection_id_to_address(collection.id)),818 );819 }820 }821822 Ok(())823 }824825 826 827 828 829 830 pub fn create_multiple_items(831 collection: &RefungibleHandle<T>,832 sender: &T::CrossAccountId,833 data: Vec<CreateItemData<T>>,834 nesting_budget: &dyn Budget,835 ) -> DispatchResult {836 if !collection.is_owner_or_admin(sender) {837 ensure!(838 collection.permissions.mint_mode(),839 <CommonError<T>>::PublicMintingNotAllowed840 );841 collection.check_allowlist(sender)?;842843 for item in data.iter() {844 for user in item.users.keys() {845 collection.check_allowlist(user)?;846 }847 }848 }849850 for item in data.iter() {851 for (owner, _) in item.users.iter() {852 <PalletCommon<T>>::ensure_correct_receiver(owner)?;853 }854 }855856 857 let totals = data858 .iter()859 .map(|data| {860 Ok(data861 .users862 .iter()863 .map(|u| u.1)864 .try_fold(0u128, |acc, v| acc.checked_add(*v))865 .ok_or(ArithmeticError::Overflow)?)866 })867 .collect::<Result<Vec<_>, DispatchError>>()?;868 for total in &totals {869 ensure!(870 *total <= MAX_REFUNGIBLE_PIECES,871 <Error<T>>::WrongRefungiblePieces872 );873 }874875 let first_token_id = <TokensMinted<T>>::get(collection.id);876 let tokens_minted = first_token_id877 .checked_add(data.len() as u32)878 .ok_or(ArithmeticError::Overflow)?;879 ensure!(880 tokens_minted < collection.limits.token_limit(),881 <CommonError<T>>::CollectionTokenLimitExceeded882 );883884 let mut balances = BTreeMap::new();885 for data in &data {886 for owner in data.users.keys() {887 let balance = balances888 .entry(owner)889 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));890 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;891892 ensure!(893 *balance <= collection.limits.account_token_ownership_limit(),894 <CommonError<T>>::AccountTokenLimitExceeded,895 );896 }897 }898899 for (i, token) in data.iter().enumerate() {900 let token_id = TokenId(first_token_id + i as u32 + 1);901 for (to, _) in token.users.iter() {902 <PalletStructure<T>>::check_nesting(903 sender.clone(),904 to,905 collection.id,906 token_id,907 nesting_budget,908 )?;909 }910 }911912 913914 with_transaction(|| {915 for (i, data) in data.iter().enumerate() {916 let token_id = first_token_id + i as u32 + 1;917 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);918919 for (user, amount) in data.users.iter() {920 if *amount == 0 {921 continue;922 }923 <Balance<T>>::insert((collection.id, token_id, &user), amount);924 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);925 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(926 user,927 collection.id,928 TokenId(token_id),929 );930 }931932 if let Err(e) = Self::set_token_properties(933 collection,934 sender,935 TokenId(token_id),936 data.properties.clone().into_iter(),937 true,938 nesting_budget,939 ) {940 return TransactionOutcome::Rollback(Err(e));941 }942 }943 TransactionOutcome::Commit(Ok(()))944 })?;945946 <TokensMinted<T>>::insert(collection.id, tokens_minted);947948 for (account, balance) in balances {949 <AccountBalance<T>>::insert((collection.id, account), balance);950 }951952 for (i, token) in data.into_iter().enumerate() {953 let token_id = first_token_id + i as u32 + 1;954955 let receivers = token956 .users957 .into_iter()958 .filter(|(_, amount)| *amount > 0)959 .collect::<Vec<_>>();960961 if let [(user, _)] = receivers.as_slice() {962 963 <PalletEvm<T>>::deposit_log(964 ERC721Events::Transfer {965 from: H160::default(),966 to: *user.as_eth(),967 token_id: token_id.into(),968 }969 .to_log(collection_id_to_address(collection.id)),970 );971 } else if let [_, ..] = receivers.as_slice() {972 973 <PalletEvm<T>>::deposit_log(974 ERC721Events::Transfer {975 from: H160::default(),976 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,977 token_id: token_id.into(),978 }979 .to_log(collection_id_to_address(collection.id)),980 );981 }982983 for (user, amount) in receivers.into_iter() {984 <PalletEvm<T>>::deposit_log(985 ERC20Events::Transfer {986 from: H160::default(),987 to: *user.as_eth(),988 value: amount.into(),989 }990 .to_log(T::EvmTokenAddressMapping::token_to_address(991 collection.id,992 TokenId(token_id),993 )),994 );995 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(996 collection.id,997 TokenId(token_id),998 user,999 amount,1000 ));1001 }1002 }1003 Ok(())1004 }10051006 pub fn set_allowance_unchecked(1007 collection: &RefungibleHandle<T>,1008 sender: &T::CrossAccountId,1009 spender: &T::CrossAccountId,1010 token: TokenId,1011 amount: u128,1012 ) {1013 if amount == 0 {1014 <Allowance<T>>::remove((collection.id, token, sender, spender));1015 } else {1016 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);1017 }10181019 <PalletEvm<T>>::deposit_log(1020 ERC20Events::Approval {1021 owner: *sender.as_eth(),1022 spender: *spender.as_eth(),1023 value: amount.into(),1024 }1025 .to_log(T::EvmTokenAddressMapping::token_to_address(1026 collection.id,1027 token,1028 )),1029 );1030 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1031 collection.id,1032 token,1033 sender.clone(),1034 spender.clone(),1035 amount,1036 ))1037 }10381039 1040 1041 1042 pub fn set_allowance(1043 collection: &RefungibleHandle<T>,1044 sender: &T::CrossAccountId,1045 spender: &T::CrossAccountId,1046 token: TokenId,1047 amount: u128,1048 ) -> DispatchResult {1049 if collection.permissions.access() == AccessMode::AllowList {1050 collection.check_allowlist(sender)?;1051 collection.check_allowlist(spender)?;1052 }10531054 <PalletCommon<T>>::ensure_correct_receiver(spender)?;10551056 if <Balance<T>>::get((collection.id, token, sender)) < amount {1057 ensure!(1058 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1059 <CommonError<T>>::CantApproveMoreThanOwned1060 );1061 }10621063 10641065 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1066 Ok(())1067 }10681069 1070 1071 1072 1073 1074 pub fn set_allowance_from(1075 collection: &RefungibleHandle<T>,1076 sender: &T::CrossAccountId,1077 from: &T::CrossAccountId,1078 to: &T::CrossAccountId,1079 token_id: TokenId,1080 amount: u128,1081 ) -> DispatchResult {1082 if collection.permissions.access() == AccessMode::AllowList {1083 collection.check_allowlist(sender)?;1084 collection.check_allowlist(from)?;1085 collection.check_allowlist(to)?;1086 }10871088 <PalletCommon<T>>::ensure_correct_receiver(to)?;10891090 ensure!(1091 sender.conv_eq(from),1092 <CommonError<T>>::AddressIsNotEthMirror1093 );10941095 if <Balance<T>>::get((collection.id, token_id, from)) < amount {1096 ensure!(1097 collection.limits.owner_can_transfer()1098 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1099 && Self::token_exists(collection, token_id),1100 <CommonError<T>>::CantApproveMoreThanOwned1101 );1102 }11031104 11051106 Self::set_allowance_unchecked(collection, from, to, token_id, amount);1107 Ok(())1108 }11091110 1111 fn check_allowed(1112 collection: &RefungibleHandle<T>,1113 spender: &T::CrossAccountId,1114 from: &T::CrossAccountId,1115 token: TokenId,1116 amount: u128,1117 nesting_budget: &dyn Budget,1118 ) -> Result<Option<u128>, DispatchError> {1119 if spender.conv_eq(from) {1120 return Ok(None);1121 }1122 if collection.permissions.access() == AccessMode::AllowList {1123 1124 collection.check_allowlist(spender)?;1125 }11261127 if collection.ignores_token_restrictions(spender) {1128 return Ok(Self::compute_allowance_decrease(1129 collection, token, from, &spender, amount,1130 ));1131 }11321133 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1134 1135 ensure!(1136 <PalletStructure<T>>::check_indirectly_owned(1137 spender.clone(),1138 source.0,1139 source.1,1140 None,1141 nesting_budget1142 )?,1143 <CommonError<T>>::ApprovedValueTooLow,1144 );1145 return Ok(None);1146 }11471148 let allowance = Self::compute_allowance_decrease(collection, token, from, &spender, amount);1149 if allowance.is_some() {1150 return Ok(allowance);1151 }11521153 1154 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1155 return Ok(allowance);1156 }11571158 Err(<CommonError<T>>::ApprovedValueTooLow.into())1159 }11601161 1162 1163 fn compute_allowance_decrease(1164 collection: &RefungibleHandle<T>,1165 token: TokenId,1166 from: &T::CrossAccountId,1167 spender: &T::CrossAccountId,1168 amount: u128,1169 ) -> Option<u128> {1170 <Allowance<T>>::get((collection.id, token, from, spender)).checked_sub(amount)1171 }11721173 1174 1175 1176 1177 1178 1179 pub fn transfer_from(1180 collection: &RefungibleHandle<T>,1181 spender: &T::CrossAccountId,1182 from: &T::CrossAccountId,1183 to: &T::CrossAccountId,1184 token: TokenId,1185 amount: u128,1186 nesting_budget: &dyn Budget,1187 ) -> DispatchResult {1188 let allowance =1189 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11901191 11921193 Self::transfer(collection, from, to, token, amount, nesting_budget)?;1194 if let Some(allowance) = allowance {1195 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1196 }1197 Ok(())1198 }11991200 1201 1202 1203 1204 1205 1206 pub fn burn_from(1207 collection: &RefungibleHandle<T>,1208 spender: &T::CrossAccountId,1209 from: &T::CrossAccountId,1210 token: TokenId,1211 amount: u128,1212 nesting_budget: &dyn Budget,1213 ) -> DispatchResult {1214 let allowance =1215 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12161217 12181219 Self::burn(collection, from, token, amount)?;1220 if let Some(allowance) = allowance {1221 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1222 }1223 Ok(())1224 }12251226 1227 1228 1229 1230 1231 1232 1233 pub fn create_item(1234 collection: &RefungibleHandle<T>,1235 sender: &T::CrossAccountId,1236 data: CreateItemData<T>,1237 nesting_budget: &dyn Budget,1238 ) -> DispatchResult {1239 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1240 }12411242 1243 1244 1245 1246 1247 1248 1249 pub fn repartition(1250 collection: &RefungibleHandle<T>,1251 owner: &T::CrossAccountId,1252 token: TokenId,1253 amount: u128,1254 ) -> DispatchResult {1255 ensure!(1256 amount <= MAX_REFUNGIBLE_PIECES,1257 <Error<T>>::WrongRefungiblePieces1258 );1259 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1260 1261 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1262 let balance = <Balance<T>>::get((collection.id, token, owner));1263 ensure!(1264 total_pieces == balance,1265 <Error<T>>::RepartitionWhileNotOwningAllPieces1266 );12671268 <Balance<T>>::insert((collection.id, token, owner), amount);1269 <TotalSupply<T>>::insert((collection.id, token), amount);12701271 if amount > total_pieces {1272 let mint_amount = amount - total_pieces;1273 <PalletEvm<T>>::deposit_log(1274 ERC20Events::Transfer {1275 from: H160::default(),1276 to: *owner.as_eth(),1277 value: mint_amount.into(),1278 }1279 .to_log(T::EvmTokenAddressMapping::token_to_address(1280 collection.id,1281 token,1282 )),1283 );1284 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1285 collection.id,1286 token,1287 owner.clone(),1288 mint_amount,1289 ));1290 } else if total_pieces > amount {1291 let burn_amount = total_pieces - amount;1292 <PalletEvm<T>>::deposit_log(1293 ERC20Events::Transfer {1294 from: *owner.as_eth(),1295 to: H160::default(),1296 value: burn_amount.into(),1297 }1298 .to_log(T::EvmTokenAddressMapping::token_to_address(1299 collection.id,1300 token,1301 )),1302 );1303 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1304 collection.id,1305 token,1306 owner.clone(),1307 burn_amount,1308 ));1309 }13101311 Ok(())1312 }13131314 fn token_owner(1315 collection_id: CollectionId,1316 token_id: TokenId,1317 ) -> Result<T::CrossAccountId, TokenOwnerError> {1318 let mut owner = None;1319 let mut count = 0;1320 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1321 count += 1;1322 if count > 1 {1323 return Err(TokenOwnerError::MultipleOwners);1324 }1325 owner = Some(key);1326 }1327 owner.ok_or(TokenOwnerError::NotFound)1328 }13291330 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1331 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1332 }13331334 pub fn set_collection_properties(1335 collection: &RefungibleHandle<T>,1336 sender: &T::CrossAccountId,1337 properties: Vec<Property>,1338 ) -> DispatchResult {1339 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())1340 }13411342 pub fn delete_collection_properties(1343 collection: &RefungibleHandle<T>,1344 sender: &T::CrossAccountId,1345 property_keys: Vec<PropertyKey>,1346 ) -> DispatchResult {1347 <PalletCommon<T>>::delete_collection_properties(1348 collection,1349 sender,1350 property_keys.into_iter(),1351 )1352 }13531354 pub fn set_token_property_permissions(1355 collection: &RefungibleHandle<T>,1356 sender: &T::CrossAccountId,1357 property_permissions: Vec<PropertyKeyPermission>,1358 ) -> DispatchResult {1359 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1360 }13611362 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1363 <PalletCommon<T>>::property_permissions(collection_id)1364 }13651366 pub fn set_scoped_token_property_permissions(1367 collection: &RefungibleHandle<T>,1368 sender: &T::CrossAccountId,1369 scope: PropertyScope,1370 property_permissions: Vec<PropertyKeyPermission>,1371 ) -> DispatchResult {1372 <PalletCommon<T>>::set_scoped_token_property_permissions(1373 collection,1374 sender,1375 scope,1376 property_permissions,1377 )1378 }13791380 1381 1382 1383 1384 1385 1386 pub fn token_owners(1387 collection_id: CollectionId,1388 token: TokenId,1389 ) -> Option<Vec<T::CrossAccountId>> {1390 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1391 .map(|(owner, _amount)| owner)1392 .take(10)1393 .collect();13941395 if res.is_empty() {1396 None1397 } else {1398 Some(res)1399 }1400 }14011402 1403 1404 1405 1406 1407 1408 pub fn set_allowance_for_all(1409 collection: &RefungibleHandle<T>,1410 owner: &T::CrossAccountId,1411 spender: &T::CrossAccountId,1412 approve: bool,1413 ) -> DispatchResult {1414 <PalletCommon<T>>::set_allowance_for_all(1415 collection,1416 owner,1417 spender,1418 approve,1419 || <CollectionAllowance<T>>::insert((collection.id, owner, spender), approve),1420 ERC721Events::ApprovalForAll {1421 owner: *owner.as_eth(),1422 operator: *spender.as_eth(),1423 approved: approve,1424 }1425 .to_log(collection_id_to_address(collection.id)),1426 )1427 }14281429 1430 pub fn allowance_for_all(1431 collection: &RefungibleHandle<T>,1432 owner: &T::CrossAccountId,1433 spender: &T::CrossAccountId,1434 ) -> bool {1435 <CollectionAllowance<T>>::get((collection.id, owner, spender))1436 }14371438 pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1439 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1440 properties.recompute_consumed_space();1441 });14421443 Ok(())1444 }1445}