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, fail, 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, erc::CollectionHelpersEvents,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, PropertyPermission, PropertyScope, PropertyValue, TokenId,110 TrySetProperty, PropertiesPermissionMap, CreateRefungibleExMultipleOwners,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 Some(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 #[transactional]519 fn modify_token_properties(520 collection: &RefungibleHandle<T>,521 sender: &T::CrossAccountId,522 token_id: TokenId,523 properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,524 is_token_create: bool,525 nesting_budget: &dyn Budget,526 ) -> DispatchResult {527 let is_collection_admin = || collection.is_owner_or_admin(sender);528 let is_token_owner = || -> Result<bool, DispatchError> {529 let balance = collection.balance(sender.clone(), token_id);530 let total_pieces: u128 =531 Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);532 if balance != total_pieces {533 return Ok(false);534 }535536 let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(537 sender.clone(),538 collection.id,539 token_id,540 None,541 nesting_budget,542 )?;543544 Ok(is_bundle_owner)545 };546547 for (key, value) in properties {548 let permission = <PalletCommon<T>>::property_permissions(collection.id)549 .get(&key)550 .cloned()551 .unwrap_or_else(PropertyPermission::none);552553 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))554 .get(&key)555 .is_some();556557 match permission {558 PropertyPermission { mutable: false, .. } if is_property_exists => {559 return Err(<CommonError<T>>::NoPermission.into());560 }561562 PropertyPermission {563 collection_admin,564 token_owner,565 ..566 } => {567 568 let is_token_create =569 is_token_create && (collection_admin || token_owner) && value.is_some();570 if !(is_token_create571 || (collection_admin && is_collection_admin())572 || (token_owner && is_token_owner()?))573 {574 fail!(<CommonError<T>>::NoPermission);575 }576 }577 }578579 match value {580 Some(value) => {581 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {582 properties.try_set(key.clone(), value)583 })584 .map_err(<CommonError<T>>::from)?;585586 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(587 collection.id,588 token_id,589 key,590 ));591 }592 None => {593 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {594 properties.remove(&key)595 })596 .map_err(<CommonError<T>>::from)?;597598 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(599 collection.id,600 token_id,601 key,602 ));603 }604 }605606 <PalletEvm<T>>::deposit_log(607 CollectionHelpersEvents::TokenChanged {608 collection_id: collection_id_to_address(collection.id),609 token_id: token_id.into(),610 }611 .to_log(T::ContractAddress::get()),612 );613 }614615 Ok(())616 }617618 pub fn set_token_properties(619 collection: &RefungibleHandle<T>,620 sender: &T::CrossAccountId,621 token_id: TokenId,622 properties: impl Iterator<Item = Property>,623 is_token_create: bool,624 nesting_budget: &dyn Budget,625 ) -> DispatchResult {626 Self::modify_token_properties(627 collection,628 sender,629 token_id,630 properties.map(|p| (p.key, Some(p.value))),631 is_token_create,632 nesting_budget,633 )634 }635636 pub fn set_token_property(637 collection: &RefungibleHandle<T>,638 sender: &T::CrossAccountId,639 token_id: TokenId,640 property: Property,641 nesting_budget: &dyn Budget,642 ) -> DispatchResult {643 let is_token_create = false;644645 Self::set_token_properties(646 collection,647 sender,648 token_id,649 [property].into_iter(),650 is_token_create,651 nesting_budget,652 )653 }654655 pub fn delete_token_properties(656 collection: &RefungibleHandle<T>,657 sender: &T::CrossAccountId,658 token_id: TokenId,659 property_keys: impl Iterator<Item = PropertyKey>,660 nesting_budget: &dyn Budget,661 ) -> DispatchResult {662 let is_token_create = false;663664 Self::modify_token_properties(665 collection,666 sender,667 token_id,668 property_keys.into_iter().map(|key| (key, None)),669 is_token_create,670 nesting_budget,671 )672 }673674 pub fn delete_token_property(675 collection: &RefungibleHandle<T>,676 sender: &T::CrossAccountId,677 token_id: TokenId,678 property_key: PropertyKey,679 nesting_budget: &dyn Budget,680 ) -> DispatchResult {681 Self::delete_token_properties(682 collection,683 sender,684 token_id,685 [property_key].into_iter(),686 nesting_budget,687 )688 }689690 691 692 693 694 695 696 697 698 699 pub fn transfer(700 collection: &RefungibleHandle<T>,701 from: &T::CrossAccountId,702 to: &T::CrossAccountId,703 token: TokenId,704 amount: u128,705 nesting_budget: &dyn Budget,706 ) -> DispatchResult {707 ensure!(708 collection.limits.transfers_enabled(),709 <CommonError<T>>::TransferNotAllowed710 );711712 if collection.permissions.access() == AccessMode::AllowList {713 collection.check_allowlist(from)?;714 collection.check_allowlist(to)?;715 }716 <PalletCommon<T>>::ensure_correct_receiver(to)?;717718 let initial_balance_from = <Balance<T>>::get((collection.id, token, from));719720 if initial_balance_from == 0 {721 return Err(<CommonError<T>>::TokenValueTooLow.into());722 }723724 let updated_balance_from = initial_balance_from725 .checked_sub(amount)726 .ok_or(<CommonError<T>>::TokenValueTooLow)?;727 let mut create_target = false;728 let from_to_differ = from != to;729 let updated_balance_to = if from != to && amount != 0 {730 let old_balance = <Balance<T>>::get((collection.id, token, to));731 if old_balance == 0 {732 create_target = true;733 }734 Some(735 old_balance736 .checked_add(amount)737 .ok_or(ArithmeticError::Overflow)?,738 )739 } else {740 None741 };742743 let account_balance_from = if updated_balance_from == 0 {744 Some(745 <AccountBalance<T>>::get((collection.id, from))746 .checked_sub(1)747 748 .ok_or(ArithmeticError::Underflow)?,749 )750 } else {751 None752 };753 754 755 let account_balance_to = if create_target && from_to_differ {756 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))757 .checked_add(1)758 .ok_or(ArithmeticError::Overflow)?;759 ensure!(760 account_balance_to < collection.limits.account_token_ownership_limit(),761 <CommonError<T>>::AccountTokenLimitExceeded,762 );763764 Some(account_balance_to)765 } else {766 None767 };768769 770771 if let Some(updated_balance_to) = updated_balance_to {772 773774 <PalletStructure<T>>::nest_if_sent_to_token(775 from.clone(),776 to,777 collection.id,778 token,779 nesting_budget,780 )?;781782 if updated_balance_from == 0 {783 <Balance<T>>::remove((collection.id, token, from));784 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);785 } else {786 <Balance<T>>::insert((collection.id, token, from), updated_balance_from);787 }788 <Balance<T>>::insert((collection.id, token, to), updated_balance_to);789 if let Some(account_balance_from) = account_balance_from {790 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);791 <Owned<T>>::remove((collection.id, from, token));792 }793 if let Some(account_balance_to) = account_balance_to {794 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);795 <Owned<T>>::insert((collection.id, to, token), true);796 }797 }798799 <PalletEvm<T>>::deposit_log(800 ERC20Events::Transfer {801 from: *from.as_eth(),802 to: *to.as_eth(),803 value: amount.into(),804 }805 .to_log(T::EvmTokenAddressMapping::token_to_address(806 collection.id,807 token,808 )),809 );810811 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(812 collection.id,813 token,814 from.clone(),815 to.clone(),816 amount,817 ));818819 let total_supply = <TotalSupply<T>>::get((collection.id, token));820821 if amount == total_supply {822 823 <PalletEvm<T>>::deposit_log(824 ERC721Events::Transfer {825 from: *from.as_eth(),826 to: *to.as_eth(),827 token_id: token.into(),828 }829 .to_log(collection_id_to_address(collection.id)),830 );831 } else if let Some(updated_balance_to) = updated_balance_to {832 833 834 if initial_balance_from == total_supply {835 836 837 <PalletEvm<T>>::deposit_log(838 ERC721Events::Transfer {839 from: *from.as_eth(),840 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,841 token_id: token.into(),842 }843 .to_log(collection_id_to_address(collection.id)),844 );845 } else if updated_balance_to == total_supply {846 847 <PalletEvm<T>>::deposit_log(848 ERC721Events::Transfer {849 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,850 to: *to.as_eth(),851 token_id: token.into(),852 }853 .to_log(collection_id_to_address(collection.id)),854 );855 }856 }857858 Ok(())859 }860861 862 863 864 865 866 pub fn create_multiple_items(867 collection: &RefungibleHandle<T>,868 sender: &T::CrossAccountId,869 data: Vec<CreateItemData<T>>,870 nesting_budget: &dyn Budget,871 ) -> DispatchResult {872 if !collection.is_owner_or_admin(sender) {873 ensure!(874 collection.permissions.mint_mode(),875 <CommonError<T>>::PublicMintingNotAllowed876 );877 collection.check_allowlist(sender)?;878879 for item in data.iter() {880 for user in item.users.keys() {881 collection.check_allowlist(user)?;882 }883 }884 }885886 for item in data.iter() {887 for (owner, _) in item.users.iter() {888 <PalletCommon<T>>::ensure_correct_receiver(owner)?;889 }890 }891892 893 let totals = data894 .iter()895 .map(|data| {896 Ok(data897 .users898 .iter()899 .map(|u| u.1)900 .try_fold(0u128, |acc, v| acc.checked_add(*v))901 .ok_or(ArithmeticError::Overflow)?)902 })903 .collect::<Result<Vec<_>, DispatchError>>()?;904 for total in &totals {905 ensure!(906 *total <= MAX_REFUNGIBLE_PIECES,907 <Error<T>>::WrongRefungiblePieces908 );909 }910911 let first_token_id = <TokensMinted<T>>::get(collection.id);912 let tokens_minted = first_token_id913 .checked_add(data.len() as u32)914 .ok_or(ArithmeticError::Overflow)?;915 ensure!(916 tokens_minted < collection.limits.token_limit(),917 <CommonError<T>>::CollectionTokenLimitExceeded918 );919920 let mut balances = BTreeMap::new();921 for data in &data {922 for owner in data.users.keys() {923 let balance = balances924 .entry(owner)925 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));926 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;927928 ensure!(929 *balance <= collection.limits.account_token_ownership_limit(),930 <CommonError<T>>::AccountTokenLimitExceeded,931 );932 }933 }934935 for (i, token) in data.iter().enumerate() {936 let token_id = TokenId(first_token_id + i as u32 + 1);937 for (to, _) in token.users.iter() {938 <PalletStructure<T>>::check_nesting(939 sender.clone(),940 to,941 collection.id,942 token_id,943 nesting_budget,944 )?;945 }946 }947948 949950 with_transaction(|| {951 for (i, data) in data.iter().enumerate() {952 let token_id = first_token_id + i as u32 + 1;953 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);954955 for (user, amount) in data.users.iter() {956 if *amount == 0 {957 continue;958 }959 <Balance<T>>::insert((collection.id, token_id, &user), amount);960 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);961 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(962 user,963 collection.id,964 TokenId(token_id),965 );966 }967968 if let Err(e) = Self::set_token_properties(969 collection,970 sender,971 TokenId(token_id),972 data.properties.clone().into_iter(),973 true,974 nesting_budget,975 ) {976 return TransactionOutcome::Rollback(Err(e));977 }978 }979 TransactionOutcome::Commit(Ok(()))980 })?;981982 <TokensMinted<T>>::insert(collection.id, tokens_minted);983984 for (account, balance) in balances {985 <AccountBalance<T>>::insert((collection.id, account), balance);986 }987988 for (i, token) in data.into_iter().enumerate() {989 let token_id = first_token_id + i as u32 + 1;990991 let receivers = token992 .users993 .into_iter()994 .filter(|(_, amount)| *amount > 0)995 .collect::<Vec<_>>();996997 if let [(user, _)] = receivers.as_slice() {998 999 <PalletEvm<T>>::deposit_log(1000 ERC721Events::Transfer {1001 from: H160::default(),1002 to: *user.as_eth(),1003 token_id: token_id.into(),1004 }1005 .to_log(collection_id_to_address(collection.id)),1006 );1007 } else if let [_, ..] = receivers.as_slice() {1008 1009 <PalletEvm<T>>::deposit_log(1010 ERC721Events::Transfer {1011 from: H160::default(),1012 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,1013 token_id: token_id.into(),1014 }1015 .to_log(collection_id_to_address(collection.id)),1016 );1017 }10181019 for (user, amount) in receivers.into_iter() {1020 <PalletEvm<T>>::deposit_log(1021 ERC20Events::Transfer {1022 from: H160::default(),1023 to: *user.as_eth(),1024 value: amount.into(),1025 }1026 .to_log(T::EvmTokenAddressMapping::token_to_address(1027 collection.id,1028 TokenId(token_id),1029 )),1030 );1031 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1032 collection.id,1033 TokenId(token_id),1034 user,1035 amount,1036 ));1037 }1038 }1039 Ok(())1040 }10411042 pub fn set_allowance_unchecked(1043 collection: &RefungibleHandle<T>,1044 sender: &T::CrossAccountId,1045 spender: &T::CrossAccountId,1046 token: TokenId,1047 amount: u128,1048 ) {1049 if amount == 0 {1050 <Allowance<T>>::remove((collection.id, token, sender, spender));1051 } else {1052 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);1053 }10541055 <PalletEvm<T>>::deposit_log(1056 ERC20Events::Approval {1057 owner: *sender.as_eth(),1058 spender: *spender.as_eth(),1059 value: amount.into(),1060 }1061 .to_log(T::EvmTokenAddressMapping::token_to_address(1062 collection.id,1063 token,1064 )),1065 );1066 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1067 collection.id,1068 token,1069 sender.clone(),1070 spender.clone(),1071 amount,1072 ))1073 }10741075 1076 1077 1078 pub fn set_allowance(1079 collection: &RefungibleHandle<T>,1080 sender: &T::CrossAccountId,1081 spender: &T::CrossAccountId,1082 token: TokenId,1083 amount: u128,1084 ) -> DispatchResult {1085 if collection.permissions.access() == AccessMode::AllowList {1086 collection.check_allowlist(sender)?;1087 collection.check_allowlist(spender)?;1088 }10891090 <PalletCommon<T>>::ensure_correct_receiver(spender)?;10911092 if <Balance<T>>::get((collection.id, token, sender)) < amount {1093 ensure!(1094 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1095 <CommonError<T>>::CantApproveMoreThanOwned1096 );1097 }10981099 11001101 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1102 Ok(())1103 }11041105 1106 1107 1108 1109 1110 pub fn set_allowance_for(1111 collection: &RefungibleHandle<T>,1112 sender: &T::CrossAccountId,1113 from: &T::CrossAccountId,1114 to: &T::CrossAccountId,1115 token_id: TokenId,1116 amount: u128,1117 ) -> DispatchResult {1118 if collection.permissions.access() == AccessMode::AllowList {1119 collection.check_allowlist(sender)?;1120 collection.check_allowlist(from)?;1121 collection.check_allowlist(to)?;1122 }11231124 <PalletCommon<T>>::ensure_correct_receiver(to)?;11251126 ensure!(1127 *sender.as_eth() == *from.as_eth(),1128 <CommonError<T>>::AddressIsNotEthMirror1129 );11301131 if <Balance<T>>::get((collection.id, token_id, from)) < amount {1132 ensure!(1133 collection.limits.owner_can_transfer()1134 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1135 && Self::token_exists(collection, token_id),1136 <CommonError<T>>::CantApproveMoreThanOwned1137 );1138 }11391140 11411142 Self::set_allowance_unchecked(collection, from, to, token_id, amount);1143 Ok(())1144 }11451146 1147 fn check_allowed(1148 collection: &RefungibleHandle<T>,1149 spender: &T::CrossAccountId,1150 from: &T::CrossAccountId,1151 token: TokenId,1152 amount: u128,1153 nesting_budget: &dyn Budget,1154 ) -> Result<Option<u128>, DispatchError> {1155 if spender.conv_eq(from) {1156 return Ok(None);1157 }1158 if collection.permissions.access() == AccessMode::AllowList {1159 1160 collection.check_allowlist(spender)?;1161 }1162 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1163 1164 ensure!(1165 <PalletStructure<T>>::check_indirectly_owned(1166 spender.clone(),1167 source.0,1168 source.1,1169 None,1170 nesting_budget1171 )?,1172 <CommonError<T>>::ApprovedValueTooLow,1173 );1174 return Ok(None);1175 }1176 let allowance =1177 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);11781179 1180 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1181 return Ok(allowance);1182 }11831184 if allowance.is_none() {1185 ensure!(1186 collection.ignores_allowance(spender),1187 <CommonError<T>>::ApprovedValueTooLow1188 );1189 }1190 Ok(allowance)1191 }11921193 1194 1195 1196 1197 1198 1199 pub fn transfer_from(1200 collection: &RefungibleHandle<T>,1201 spender: &T::CrossAccountId,1202 from: &T::CrossAccountId,1203 to: &T::CrossAccountId,1204 token: TokenId,1205 amount: u128,1206 nesting_budget: &dyn Budget,1207 ) -> DispatchResult {1208 let allowance =1209 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12101211 12121213 Self::transfer(collection, from, to, token, amount, nesting_budget)?;1214 if let Some(allowance) = allowance {1215 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1216 }1217 Ok(())1218 }12191220 1221 1222 1223 1224 1225 1226 pub fn burn_from(1227 collection: &RefungibleHandle<T>,1228 spender: &T::CrossAccountId,1229 from: &T::CrossAccountId,1230 token: TokenId,1231 amount: u128,1232 nesting_budget: &dyn Budget,1233 ) -> DispatchResult {1234 let allowance =1235 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12361237 12381239 Self::burn(collection, from, token, amount)?;1240 if let Some(allowance) = allowance {1241 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1242 }1243 Ok(())1244 }12451246 1247 1248 1249 1250 1251 1252 1253 pub fn create_item(1254 collection: &RefungibleHandle<T>,1255 sender: &T::CrossAccountId,1256 data: CreateItemData<T>,1257 nesting_budget: &dyn Budget,1258 ) -> DispatchResult {1259 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1260 }12611262 1263 1264 1265 1266 1267 1268 1269 pub fn repartition(1270 collection: &RefungibleHandle<T>,1271 owner: &T::CrossAccountId,1272 token: TokenId,1273 amount: u128,1274 ) -> DispatchResult {1275 ensure!(1276 amount <= MAX_REFUNGIBLE_PIECES,1277 <Error<T>>::WrongRefungiblePieces1278 );1279 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1280 1281 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1282 let balance = <Balance<T>>::get((collection.id, token, owner));1283 ensure!(1284 total_pieces == balance,1285 <Error<T>>::RepartitionWhileNotOwningAllPieces1286 );12871288 <Balance<T>>::insert((collection.id, token, owner), amount);1289 <TotalSupply<T>>::insert((collection.id, token), amount);12901291 if amount > total_pieces {1292 let mint_amount = amount - total_pieces;1293 <PalletEvm<T>>::deposit_log(1294 ERC20Events::Transfer {1295 from: H160::default(),1296 to: *owner.as_eth(),1297 value: mint_amount.into(),1298 }1299 .to_log(T::EvmTokenAddressMapping::token_to_address(1300 collection.id,1301 token,1302 )),1303 );1304 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1305 collection.id,1306 token,1307 owner.clone(),1308 mint_amount,1309 ));1310 } else if total_pieces > amount {1311 let burn_amount = total_pieces - amount;1312 <PalletEvm<T>>::deposit_log(1313 ERC20Events::Transfer {1314 from: *owner.as_eth(),1315 to: H160::default(),1316 value: burn_amount.into(),1317 }1318 .to_log(T::EvmTokenAddressMapping::token_to_address(1319 collection.id,1320 token,1321 )),1322 );1323 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1324 collection.id,1325 token,1326 owner.clone(),1327 burn_amount,1328 ));1329 }13301331 Ok(())1332 }13331334 fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1335 let mut owner = None;1336 let mut count = 0;1337 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1338 count += 1;1339 if count > 1 {1340 return None;1341 }1342 owner = Some(key);1343 }1344 owner1345 }13461347 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1348 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1349 }13501351 pub fn set_collection_properties(1352 collection: &RefungibleHandle<T>,1353 sender: &T::CrossAccountId,1354 properties: Vec<Property>,1355 ) -> DispatchResult {1356 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)1357 }13581359 pub fn delete_collection_properties(1360 collection: &RefungibleHandle<T>,1361 sender: &T::CrossAccountId,1362 property_keys: Vec<PropertyKey>,1363 ) -> DispatchResult {1364 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1365 }13661367 pub fn set_token_property_permissions(1368 collection: &RefungibleHandle<T>,1369 sender: &T::CrossAccountId,1370 property_permissions: Vec<PropertyKeyPermission>,1371 ) -> DispatchResult {1372 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1373 }13741375 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1376 <PalletCommon<T>>::property_permissions(collection_id)1377 }13781379 pub fn set_scoped_token_property_permissions(1380 collection: &RefungibleHandle<T>,1381 sender: &T::CrossAccountId,1382 scope: PropertyScope,1383 property_permissions: Vec<PropertyKeyPermission>,1384 ) -> DispatchResult {1385 <PalletCommon<T>>::set_scoped_token_property_permissions(1386 collection,1387 sender,1388 scope,1389 property_permissions,1390 )1391 }13921393 1394 1395 1396 1397 1398 1399 pub fn token_owners(1400 collection_id: CollectionId,1401 token: TokenId,1402 ) -> Option<Vec<T::CrossAccountId>> {1403 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1404 .map(|(owner, _amount)| owner)1405 .take(10)1406 .collect();14071408 if res.is_empty() {1409 None1410 } else {1411 Some(res)1412 }1413 }14141415 1416 1417 1418 1419 1420 1421 pub fn set_allowance_for_all(1422 collection: &RefungibleHandle<T>,1423 owner: &T::CrossAccountId,1424 operator: &T::CrossAccountId,1425 approve: bool,1426 ) -> DispatchResult {1427 if collection.permissions.access() == AccessMode::AllowList {1428 collection.check_allowlist(owner)?;1429 collection.check_allowlist(operator)?;1430 }14311432 <PalletCommon<T>>::ensure_correct_receiver(operator)?;14331434 14351436 <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve);1437 <PalletEvm<T>>::deposit_log(1438 ERC721Events::ApprovalForAll {1439 owner: *owner.as_eth(),1440 operator: *operator.as_eth(),1441 approved: approve,1442 }1443 .to_log(collection_id_to_address(collection.id)),1444 );1445 <PalletCommon<T>>::deposit_event(CommonEvent::ApprovedForAll(1446 collection.id,1447 owner.clone(),1448 operator.clone(),1449 approve,1450 ));1451 Ok(())1452 }14531454 1455 pub fn allowance_for_all(1456 collection: &RefungibleHandle<T>,1457 owner: &T::CrossAccountId,1458 operator: &T::CrossAccountId,1459 ) -> bool {1460 <CollectionAllowance<T>>::get((collection.id, owner, operator))1461 }14621463 pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1464 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1465 properties.recompute_consumed_space();1466 });14671468 Ok(())1469 }1470}