12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788#![cfg_attr(not(feature = "std"), no_std)]8990use crate::erc_token::ERC20Events;91use crate::erc::ERC721Events;9293use codec::{Encode, Decode, MaxEncodedLen};94use core::ops::Deref;95use evm_coder::ToLog;96use frame_support::{BoundedVec, ensure, fail, storage::with_transaction, transactional};97use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};98use pallet_evm_coder_substrate::WithRecorder;99use pallet_common::{100 CommonCollectionOperations, Error as CommonError, Event as CommonEvent,101 eth::collection_id_to_address, Pallet as PalletCommon,102};103use pallet_structure::Pallet as PalletStructure;104use scale_info::TypeInfo;105use sp_core::H160;106use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};107use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};108use up_data_structs::{109 AccessMode, budget::Budget, CollectionId, CreateCollectionData, CreateRefungibleExData,110 CustomDataLimit, mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, TokenId, Property,111 PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,112 TrySetProperty,113};114115pub use pallet::*;116#[cfg(feature = "runtime-benchmarks")]117pub mod benchmarking;118pub mod common;119pub mod erc;120pub mod erc_token;121pub mod weights;122123pub type CreateItemData<T> =124 CreateRefungibleExData<<T as pallet_evm::account::Config>::CrossAccountId>;125pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;126127128129#[struct_versioning::versioned(version = 2, upper)]130#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]131pub struct ItemData {132 pub const_data: BoundedVec<u8, CustomDataLimit>,133134 #[version(..2)]135 pub variable_data: BoundedVec<u8, CustomDataLimit>,136}137138#[frame_support::pallet]139pub mod pallet {140 use super::*;141 use frame_support::{142 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,143 traits::StorageVersion,144 };145 use frame_system::pallet_prelude::*;146 use up_data_structs::{CollectionId, TokenId};147 use super::weights::WeightInfo;148149 #[pallet::error]150 pub enum Error<T> {151 152 NotRefungibleDataUsedToMintFungibleCollectionToken,153 154 WrongRefungiblePieces,155 156 RepartitionWhileNotOwningAllPieces,157 158 RefungibleDisallowsNesting,159 160 SettingPropertiesNotAllowed,161 }162163 #[pallet::config]164 pub trait Config:165 frame_system::Config + pallet_common::Config + pallet_structure::Config166 {167 type WeightInfo: WeightInfo;168 }169170 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);171172 #[pallet::pallet]173 #[pallet::storage_version(STORAGE_VERSION)]174 #[pallet::generate_store(pub(super) trait Store)]175 pub struct Pallet<T>(_);176177 178 #[pallet::storage]179 pub type TokensMinted<T: Config> =180 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;181182 183 #[pallet::storage]184 pub type TokensBurnt<T: Config> =185 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;186187 188 #[pallet::storage]189 pub type TokenData<T: Config> = StorageNMap<190 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),191 Value = ItemData,192 QueryKind = ValueQuery,193 >;194195 196 #[pallet::storage]197 #[pallet::getter(fn token_properties)]198 pub type TokenProperties<T: Config> = StorageNMap<199 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),200 Value = up_data_structs::Properties,201 QueryKind = ValueQuery,202 OnEmpty = up_data_structs::TokenProperties,203 >;204205 206 #[pallet::storage]207 pub type TotalSupply<T: Config> = StorageNMap<208 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),209 Value = u128,210 QueryKind = ValueQuery,211 >;212213 214 #[pallet::storage]215 pub type Owned<T: Config> = StorageNMap<216 Key = (217 Key<Twox64Concat, CollectionId>,218 Key<Blake2_128Concat, T::CrossAccountId>,219 Key<Twox64Concat, TokenId>,220 ),221 Value = bool,222 QueryKind = ValueQuery,223 >;224225 226 #[pallet::storage]227 pub type AccountBalance<T: Config> = StorageNMap<228 Key = (229 Key<Twox64Concat, CollectionId>,230 231 Key<Blake2_128Concat, T::CrossAccountId>,232 ),233 Value = u32,234 QueryKind = ValueQuery,235 >;236237 238 #[pallet::storage]239 pub type Balance<T: Config> = StorageNMap<240 Key = (241 Key<Twox64Concat, CollectionId>,242 Key<Twox64Concat, TokenId>,243 244 Key<Blake2_128Concat, T::CrossAccountId>,245 ),246 Value = u128,247 QueryKind = ValueQuery,248 >;249250 251 #[pallet::storage]252 pub type Allowance<T: Config> = StorageNMap<253 Key = (254 Key<Twox64Concat, CollectionId>,255 Key<Twox64Concat, TokenId>,256 257 Key<Blake2_128, T::CrossAccountId>,258 259 Key<Blake2_128Concat, T::CrossAccountId>,260 ),261 Value = u128,262 QueryKind = ValueQuery,263 >;264265 #[pallet::hooks]266 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {267 fn on_runtime_upgrade() -> Weight {268 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {269 <TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {270 Some(<ItemDataVersion2>::from(v))271 })272 }273274 0275 }276 }277}278279pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);280impl<T: Config> RefungibleHandle<T> {281 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {282 Self(inner)283 }284 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {285 self.0286 }287 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {288 &mut self.0289 }290}291292impl<T: Config> Deref for RefungibleHandle<T> {293 type Target = pallet_common::CollectionHandle<T>;294295 fn deref(&self) -> &Self::Target {296 &self.0297 }298}299300impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {301 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {302 self.0.recorder()303 }304 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {305 self.0.into_recorder()306 }307}308309impl<T: Config> Pallet<T> {310 311 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {312 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)313 }314315 316 317 318 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {319 <TotalSupply<T>>::contains_key((collection.id, token))320 }321322 pub fn set_scoped_token_property(323 collection_id: CollectionId,324 token_id: TokenId,325 scope: PropertyScope,326 property: Property,327 ) -> DispatchResult {328 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {329 properties.try_scoped_set(scope, property.key, property.value)330 })331 .map_err(<CommonError<T>>::from)?;332333 Ok(())334 }335336 pub fn set_scoped_token_properties(337 collection_id: CollectionId,338 token_id: TokenId,339 scope: PropertyScope,340 properties: impl Iterator<Item = Property>,341 ) -> DispatchResult {342 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {343 stored_properties.try_scoped_set_from_iter(scope, properties)344 })345 .map_err(<CommonError<T>>::from)?;346347 Ok(())348 }349}350351352impl<T: Config> Pallet<T> {353 354 355 356 357 358 pub fn init_collection(359 owner: T::CrossAccountId,360 data: CreateCollectionData<T::AccountId>,361 ) -> Result<CollectionId, DispatchError> {362 <PalletCommon<T>>::init_collection(owner, data, false)363 }364365 366 367 368 369 pub fn destroy_collection(370 collection: RefungibleHandle<T>,371 sender: &T::CrossAccountId,372 ) -> DispatchResult {373 let id = collection.id;374375 if Self::collection_has_tokens(id) {376 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());377 }378379 380381 PalletCommon::destroy_collection(collection.0, sender)?;382383 <TokensMinted<T>>::remove(id);384 <TokensBurnt<T>>::remove(id);385 <TokenData<T>>::remove_prefix((id,), None);386 <TotalSupply<T>>::remove_prefix((id,), None);387 <Balance<T>>::remove_prefix((id,), None);388 <Allowance<T>>::remove_prefix((id,), None);389 <Owned<T>>::remove_prefix((id,), None);390 <AccountBalance<T>>::remove_prefix((id,), None);391 Ok(())392 }393394 fn collection_has_tokens(collection_id: CollectionId) -> bool {395 <TokenData<T>>::iter_prefix((collection_id,))396 .next()397 .is_some()398 }399400 pub fn burn_token_unchecked(401 collection: &RefungibleHandle<T>,402 token_id: TokenId,403 ) -> DispatchResult {404 let burnt = <TokensBurnt<T>>::get(collection.id)405 .checked_add(1)406 .ok_or(ArithmeticError::Overflow)?;407408 <TokensBurnt<T>>::insert(collection.id, burnt);409 <TokenData<T>>::remove((collection.id, token_id));410 <TokenProperties<T>>::remove((collection.id, token_id));411 <TotalSupply<T>>::remove((collection.id, token_id));412 <Balance<T>>::remove_prefix((collection.id, token_id), None);413 <Allowance<T>>::remove_prefix((collection.id, token_id), None);414 415 Ok(())416 }417418 419 420 421 422 423 424 425 426 427 428 429 pub fn burn(430 collection: &RefungibleHandle<T>,431 owner: &T::CrossAccountId,432 token: TokenId,433 amount: u128,434 ) -> DispatchResult {435 let total_supply = <TotalSupply<T>>::get((collection.id, token))436 .checked_sub(amount)437 .ok_or(<CommonError<T>>::TokenValueTooLow)?;438439 440 if total_supply == 0 {441 442 ensure!(443 <Balance<T>>::get((collection.id, token, owner)) == amount,444 <CommonError<T>>::TokenValueTooLow445 );446 let account_balance = <AccountBalance<T>>::get((collection.id, owner))447 .checked_sub(1)448 449 .ok_or(ArithmeticError::Underflow)?;450451 452453 <Owned<T>>::remove((collection.id, owner, token));454 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);455 <AccountBalance<T>>::insert((collection.id, owner), account_balance);456 Self::burn_token_unchecked(collection, token)?;457 <PalletEvm<T>>::deposit_log(458 ERC721Events::Transfer {459 from: *owner.as_eth(),460 to: H160::default(),461 token_id: token.into(),462 }463 .to_log(collection_id_to_address(collection.id)),464 );465 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(466 collection.id,467 token,468 owner.clone(),469 amount,470 ));471 return Ok(());472 }473474 let balance = <Balance<T>>::get((collection.id, token, owner))475 .checked_sub(amount)476 .ok_or(<CommonError<T>>::TokenValueTooLow)?;477 let account_balance = if balance == 0 {478 <AccountBalance<T>>::get((collection.id, owner))479 .checked_sub(1)480 481 .ok_or(ArithmeticError::Underflow)?482 } else {483 0484 };485486 487488 if balance == 0 {489 <Owned<T>>::remove((collection.id, owner, token));490 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);491 <Balance<T>>::remove((collection.id, token, owner));492 <AccountBalance<T>>::insert((collection.id, owner), account_balance);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 }605 }606607 Ok(())608 }609610 pub fn set_token_properties(611 collection: &RefungibleHandle<T>,612 sender: &T::CrossAccountId,613 token_id: TokenId,614 properties: impl Iterator<Item = Property>,615 is_token_create: bool,616 nesting_budget: &dyn Budget,617 ) -> DispatchResult {618 Self::modify_token_properties(619 collection,620 sender,621 token_id,622 properties.map(|p| (p.key, Some(p.value))),623 is_token_create,624 nesting_budget,625 )626 }627628 pub fn set_token_property(629 collection: &RefungibleHandle<T>,630 sender: &T::CrossAccountId,631 token_id: TokenId,632 property: Property,633 nesting_budget: &dyn Budget,634 ) -> DispatchResult {635 let is_token_create = false;636637 Self::set_token_properties(638 collection,639 sender,640 token_id,641 [property].into_iter(),642 is_token_create,643 nesting_budget,644 )645 }646647 pub fn delete_token_properties(648 collection: &RefungibleHandle<T>,649 sender: &T::CrossAccountId,650 token_id: TokenId,651 property_keys: impl Iterator<Item = PropertyKey>,652 nesting_budget: &dyn Budget,653 ) -> DispatchResult {654 let is_token_create = false;655656 Self::modify_token_properties(657 collection,658 sender,659 token_id,660 property_keys.into_iter().map(|key| (key, None)),661 is_token_create,662 nesting_budget,663 )664 }665666 pub fn delete_token_property(667 collection: &RefungibleHandle<T>,668 sender: &T::CrossAccountId,669 token_id: TokenId,670 property_key: PropertyKey,671 nesting_budget: &dyn Budget,672 ) -> DispatchResult {673 Self::delete_token_properties(674 collection,675 sender,676 token_id,677 [property_key].into_iter(),678 nesting_budget,679 )680 }681682 683 684 685 686 687 688 689 690 691 pub fn transfer(692 collection: &RefungibleHandle<T>,693 from: &T::CrossAccountId,694 to: &T::CrossAccountId,695 token: TokenId,696 amount: u128,697 nesting_budget: &dyn Budget,698 ) -> DispatchResult {699 ensure!(700 collection.limits.transfers_enabled(),701 <CommonError<T>>::TransferNotAllowed702 );703704 if collection.permissions.access() == AccessMode::AllowList {705 collection.check_allowlist(from)?;706 collection.check_allowlist(to)?;707 }708 <PalletCommon<T>>::ensure_correct_receiver(to)?;709710 let initial_balance_from = <Balance<T>>::get((collection.id, token, from));711 let updated_balance_from = initial_balance_from712 .checked_sub(amount)713 .ok_or(<CommonError<T>>::TokenValueTooLow)?;714 let mut create_target = false;715 let from_to_differ = from != to;716 let updated_balance_to = if from != to {717 let old_balance = <Balance<T>>::get((collection.id, token, to));718 if old_balance == 0 {719 create_target = true;720 }721 Some(722 old_balance723 .checked_add(amount)724 .ok_or(ArithmeticError::Overflow)?,725 )726 } else {727 None728 };729730 let account_balance_from = if updated_balance_from == 0 {731 Some(732 <AccountBalance<T>>::get((collection.id, from))733 .checked_sub(1)734 735 .ok_or(ArithmeticError::Underflow)?,736 )737 } else {738 None739 };740 741 742 let account_balance_to = if create_target && from_to_differ {743 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))744 .checked_add(1)745 .ok_or(ArithmeticError::Overflow)?;746 ensure!(747 account_balance_to < collection.limits.account_token_ownership_limit(),748 <CommonError<T>>::AccountTokenLimitExceeded,749 );750751 Some(account_balance_to)752 } else {753 None754 };755756 757758 <PalletStructure<T>>::nest_if_sent_to_token(759 from.clone(),760 to,761 collection.id,762 token,763 nesting_budget,764 )?;765766 if let Some(updated_balance_to) = updated_balance_to {767 768 if updated_balance_from == 0 {769 <Balance<T>>::remove((collection.id, token, from));770 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);771 } else {772 <Balance<T>>::insert((collection.id, token, from), updated_balance_from);773 }774 <Balance<T>>::insert((collection.id, token, to), updated_balance_to);775 if let Some(account_balance_from) = account_balance_from {776 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);777 <Owned<T>>::remove((collection.id, from, token));778 }779 if let Some(account_balance_to) = account_balance_to {780 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);781 <Owned<T>>::insert((collection.id, to, token), true);782 }783 }784785 <PalletEvm<T>>::deposit_log(786 ERC20Events::Transfer {787 from: *from.as_eth(),788 to: *to.as_eth(),789 value: amount.into(),790 }791 .to_log(T::EvmTokenAddressMapping::token_to_address(792 collection.id,793 token,794 )),795 );796797 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(798 collection.id,799 token,800 from.clone(),801 to.clone(),802 amount,803 ));804805 let total_supply = <TotalSupply<T>>::get((collection.id, token));806807 if amount == total_supply {808 809 <PalletEvm<T>>::deposit_log(810 ERC721Events::Transfer {811 from: *from.as_eth(),812 to: *to.as_eth(),813 token_id: token.into(),814 }815 .to_log(collection_id_to_address(collection.id)),816 );817 } else if let Some(updated_balance_to) = updated_balance_to {818 819 820 if initial_balance_from == total_supply {821 822 823 <PalletEvm<T>>::deposit_log(824 ERC721Events::Transfer {825 from: *from.as_eth(),826 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,827 token_id: token.into(),828 }829 .to_log(collection_id_to_address(collection.id)),830 );831 } else if updated_balance_to == total_supply {832 833 <PalletEvm<T>>::deposit_log(834 ERC721Events::Transfer {835 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,836 to: *to.as_eth(),837 token_id: token.into(),838 }839 .to_log(collection_id_to_address(collection.id)),840 );841 }842 }843844 Ok(())845 }846847 848 849 850 851 852 pub fn create_multiple_items(853 collection: &RefungibleHandle<T>,854 sender: &T::CrossAccountId,855 data: Vec<CreateItemData<T>>,856 nesting_budget: &dyn Budget,857 ) -> DispatchResult {858 if !collection.is_owner_or_admin(sender) {859 ensure!(860 collection.permissions.mint_mode(),861 <CommonError<T>>::PublicMintingNotAllowed862 );863 collection.check_allowlist(sender)?;864865 for item in data.iter() {866 for user in item.users.keys() {867 collection.check_allowlist(user)?;868 }869 }870 }871872 for item in data.iter() {873 for (owner, _) in item.users.iter() {874 <PalletCommon<T>>::ensure_correct_receiver(owner)?;875 }876 }877878 879 let totals = data880 .iter()881 .map(|data| {882 Ok(data883 .users884 .iter()885 .map(|u| u.1)886 .try_fold(0u128, |acc, v| acc.checked_add(*v))887 .ok_or(ArithmeticError::Overflow)?)888 })889 .collect::<Result<Vec<_>, DispatchError>>()?;890 for total in &totals {891 ensure!(892 *total <= MAX_REFUNGIBLE_PIECES,893 <Error<T>>::WrongRefungiblePieces894 );895 }896897 let first_token_id = <TokensMinted<T>>::get(collection.id);898 let tokens_minted = first_token_id899 .checked_add(data.len() as u32)900 .ok_or(ArithmeticError::Overflow)?;901 ensure!(902 tokens_minted < collection.limits.token_limit(),903 <CommonError<T>>::CollectionTokenLimitExceeded904 );905906 let mut balances = BTreeMap::new();907 for data in &data {908 for owner in data.users.keys() {909 let balance = balances910 .entry(owner)911 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));912 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;913914 ensure!(915 *balance <= collection.limits.account_token_ownership_limit(),916 <CommonError<T>>::AccountTokenLimitExceeded,917 );918 }919 }920921 for (i, token) in data.iter().enumerate() {922 let token_id = TokenId(first_token_id + i as u32 + 1);923 for (to, _) in token.users.iter() {924 <PalletStructure<T>>::check_nesting(925 sender.clone(),926 to,927 collection.id,928 token_id,929 nesting_budget,930 )?;931 }932 }933934 935936 with_transaction(|| {937 for (i, data) in data.iter().enumerate() {938 let token_id = first_token_id + i as u32 + 1;939 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);940941 <TokenData<T>>::insert(942 (collection.id, token_id),943 ItemData {944 const_data: data.const_data.clone(),945 },946 );947948 for (user, amount) in data.users.iter() {949 if *amount == 0 {950 continue;951 }952 <Balance<T>>::insert((collection.id, token_id, &user), amount);953 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);954 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(955 user,956 collection.id,957 TokenId(token_id),958 );959 }960961 if let Err(e) = Self::set_token_properties(962 collection,963 sender,964 TokenId(token_id),965 data.properties.clone().into_iter(),966 true,967 nesting_budget,968 ) {969 return TransactionOutcome::Rollback(Err(e));970 }971 }972 TransactionOutcome::Commit(Ok(()))973 })?;974975 <TokensMinted<T>>::insert(collection.id, tokens_minted);976977 for (account, balance) in balances {978 <AccountBalance<T>>::insert((collection.id, account), balance);979 }980981 for (i, token) in data.into_iter().enumerate() {982 let token_id = first_token_id + i as u32 + 1;983984 for (user, amount) in token.users.into_iter() {985 if amount == 0 {986 continue;987 }988989 <PalletEvm<T>>::deposit_log(990 ERC20Events::Transfer {991 from: H160::default(),992 to: *user.as_eth(),993 value: amount.into(),994 }995 .to_log(T::EvmTokenAddressMapping::token_to_address(996 collection.id,997 TokenId(token_id),998 )),999 );1000 <PalletEvm<T>>::deposit_log(1001 ERC721Events::Transfer {1002 from: H160::default(),1003 to: *user.as_eth(),1004 token_id: token_id.into(),1005 }1006 .to_log(collection_id_to_address(collection.id)),1007 );1008 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1009 collection.id,1010 TokenId(token_id),1011 user,1012 amount,1013 ));1014 }1015 }1016 Ok(())1017 }10181019 pub fn set_allowance_unchecked(1020 collection: &RefungibleHandle<T>,1021 sender: &T::CrossAccountId,1022 spender: &T::CrossAccountId,1023 token: TokenId,1024 amount: u128,1025 ) {1026 if amount == 0 {1027 <Allowance<T>>::remove((collection.id, token, sender, spender));1028 } else {1029 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);1030 }10311032 <PalletEvm<T>>::deposit_log(1033 ERC20Events::Approval {1034 owner: *sender.as_eth(),1035 spender: *spender.as_eth(),1036 value: amount.into(),1037 }1038 .to_log(T::EvmTokenAddressMapping::token_to_address(1039 collection.id,1040 token,1041 )),1042 );1043 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1044 collection.id,1045 token,1046 sender.clone(),1047 spender.clone(),1048 amount,1049 ))1050 }10511052 1053 1054 1055 pub fn set_allowance(1056 collection: &RefungibleHandle<T>,1057 sender: &T::CrossAccountId,1058 spender: &T::CrossAccountId,1059 token: TokenId,1060 amount: u128,1061 ) -> DispatchResult {1062 if collection.permissions.access() == AccessMode::AllowList {1063 collection.check_allowlist(sender)?;1064 collection.check_allowlist(spender)?;1065 }10661067 <PalletCommon<T>>::ensure_correct_receiver(spender)?;10681069 if <Balance<T>>::get((collection.id, token, sender)) < amount {1070 ensure!(1071 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1072 <CommonError<T>>::CantApproveMoreThanOwned1073 );1074 }10751076 10771078 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1079 Ok(())1080 }10811082 1083 fn check_allowed(1084 collection: &RefungibleHandle<T>,1085 spender: &T::CrossAccountId,1086 from: &T::CrossAccountId,1087 token: TokenId,1088 amount: u128,1089 nesting_budget: &dyn Budget,1090 ) -> Result<Option<u128>, DispatchError> {1091 if spender.conv_eq(from) {1092 return Ok(None);1093 }1094 if collection.permissions.access() == AccessMode::AllowList {1095 1096 collection.check_allowlist(spender)?;1097 }1098 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1099 1100 ensure!(1101 <PalletStructure<T>>::check_indirectly_owned(1102 spender.clone(),1103 source.0,1104 source.1,1105 None,1106 nesting_budget1107 )?,1108 <CommonError<T>>::ApprovedValueTooLow,1109 );1110 return Ok(None);1111 }1112 let allowance =1113 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);1114 if allowance.is_none() {1115 ensure!(1116 collection.ignores_allowance(spender),1117 <CommonError<T>>::ApprovedValueTooLow1118 );1119 }1120 Ok(allowance)1121 }11221123 1124 1125 1126 1127 1128 1129 pub fn transfer_from(1130 collection: &RefungibleHandle<T>,1131 spender: &T::CrossAccountId,1132 from: &T::CrossAccountId,1133 to: &T::CrossAccountId,1134 token: TokenId,1135 amount: u128,1136 nesting_budget: &dyn Budget,1137 ) -> DispatchResult {1138 let allowance =1139 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11401141 11421143 Self::transfer(collection, from, to, token, amount, nesting_budget)?;1144 if let Some(allowance) = allowance {1145 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1146 }1147 Ok(())1148 }11491150 1151 1152 1153 1154 1155 1156 pub fn burn_from(1157 collection: &RefungibleHandle<T>,1158 spender: &T::CrossAccountId,1159 from: &T::CrossAccountId,1160 token: TokenId,1161 amount: u128,1162 nesting_budget: &dyn Budget,1163 ) -> DispatchResult {1164 let allowance =1165 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11661167 11681169 Self::burn(collection, from, token, amount)?;1170 if let Some(allowance) = allowance {1171 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1172 }1173 Ok(())1174 }11751176 1177 1178 1179 1180 1181 1182 1183 pub fn create_item(1184 collection: &RefungibleHandle<T>,1185 sender: &T::CrossAccountId,1186 data: CreateItemData<T>,1187 nesting_budget: &dyn Budget,1188 ) -> DispatchResult {1189 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1190 }11911192 1193 1194 1195 1196 1197 1198 1199 pub fn repartition(1200 collection: &RefungibleHandle<T>,1201 owner: &T::CrossAccountId,1202 token: TokenId,1203 amount: u128,1204 ) -> DispatchResult {1205 ensure!(1206 amount <= MAX_REFUNGIBLE_PIECES,1207 <Error<T>>::WrongRefungiblePieces1208 );1209 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1210 1211 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1212 let balance = <Balance<T>>::get((collection.id, token, owner));1213 ensure!(1214 total_pieces == balance,1215 <Error<T>>::RepartitionWhileNotOwningAllPieces1216 );12171218 <Balance<T>>::insert((collection.id, token, owner), amount);1219 <TotalSupply<T>>::insert((collection.id, token), amount);12201221 if amount > total_pieces {1222 let mint_amount = amount - total_pieces;1223 <PalletEvm<T>>::deposit_log(1224 ERC20Events::Transfer {1225 from: H160::default(),1226 to: *owner.as_eth(),1227 value: mint_amount.into(),1228 }1229 .to_log(T::EvmTokenAddressMapping::token_to_address(1230 collection.id,1231 token,1232 )),1233 );1234 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1235 collection.id,1236 token,1237 owner.clone(),1238 mint_amount,1239 ));1240 } else if total_pieces > amount {1241 let burn_amount = total_pieces - amount;1242 <PalletEvm<T>>::deposit_log(1243 ERC20Events::Transfer {1244 from: *owner.as_eth(),1245 to: H160::default(),1246 value: burn_amount.into(),1247 }1248 .to_log(T::EvmTokenAddressMapping::token_to_address(1249 collection.id,1250 token,1251 )),1252 );1253 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1254 collection.id,1255 token,1256 owner.clone(),1257 burn_amount,1258 ));1259 }12601261 Ok(())1262 }12631264 fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1265 let mut owner = None;1266 let mut count = 0;1267 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1268 count += 1;1269 if count > 1 {1270 return None;1271 }1272 owner = Some(key);1273 }1274 owner1275 }12761277 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1278 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1279 }12801281 pub fn set_collection_properties(1282 collection: &RefungibleHandle<T>,1283 sender: &T::CrossAccountId,1284 properties: Vec<Property>,1285 ) -> DispatchResult {1286 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)1287 }12881289 pub fn delete_collection_properties(1290 collection: &RefungibleHandle<T>,1291 sender: &T::CrossAccountId,1292 property_keys: Vec<PropertyKey>,1293 ) -> DispatchResult {1294 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1295 }12961297 pub fn set_token_property_permissions(1298 collection: &RefungibleHandle<T>,1299 sender: &T::CrossAccountId,1300 property_permissions: Vec<PropertyKeyPermission>,1301 ) -> DispatchResult {1302 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1303 }13041305 1306 1307 1308 1309 1310 1311 pub fn token_owners(1312 collection_id: CollectionId,1313 token: TokenId,1314 ) -> Option<Vec<T::CrossAccountId>> {1315 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1316 .map(|(owner, _amount)| owner)1317 .take(10)1318 .collect();13191320 if res.is_empty() {1321 None1322 } else {1323 Some(res)1324 }1325 }1326}