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 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(458 collection.id,459 token,460 owner.clone(),461 amount,462 ));463 return Ok(());464 }465466 let balance = <Balance<T>>::get((collection.id, token, owner))467 .checked_sub(amount)468 .ok_or(<CommonError<T>>::TokenValueTooLow)?;469 let account_balance = if balance == 0 {470 <AccountBalance<T>>::get((collection.id, owner))471 .checked_sub(1)472 473 .ok_or(ArithmeticError::Underflow)?474 } else {475 0476 };477478 479480 if balance == 0 {481 <Owned<T>>::remove((collection.id, owner, token));482 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);483 <Balance<T>>::remove((collection.id, token, owner));484 <AccountBalance<T>>::insert((collection.id, owner), account_balance);485 } else {486 <Balance<T>>::insert((collection.id, token, owner), balance);487 }488 <TotalSupply<T>>::insert((collection.id, token), total_supply);489490 <PalletEvm<T>>::deposit_log(491 ERC20Events::Transfer {492 from: *owner.as_eth(),493 to: H160::default(),494 value: amount.into(),495 }496 .to_log(T::EvmTokenAddressMapping::token_to_address(497 collection.id,498 token,499 )),500 );501 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(502 collection.id,503 token,504 owner.clone(),505 amount,506 ));507 Ok(())508 }509510 #[transactional]511 fn modify_token_properties(512 collection: &RefungibleHandle<T>,513 sender: &T::CrossAccountId,514 token_id: TokenId,515 properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,516 is_token_create: bool,517 nesting_budget: &dyn Budget,518 ) -> DispatchResult {519 let is_collection_admin = || collection.is_owner_or_admin(sender);520 let is_token_owner = || -> Result<bool, DispatchError> {521 let balance = collection.balance(sender.clone(), token_id);522 let total_pieces: u128 =523 Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);524 if balance != total_pieces {525 return Ok(false);526 }527528 let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(529 sender.clone(),530 collection.id,531 token_id,532 None,533 nesting_budget,534 )?;535536 Ok(is_bundle_owner)537 };538539 for (key, value) in properties {540 let permission = <PalletCommon<T>>::property_permissions(collection.id)541 .get(&key)542 .cloned()543 .unwrap_or_else(PropertyPermission::none);544545 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))546 .get(&key)547 .is_some();548549 match permission {550 PropertyPermission { mutable: false, .. } if is_property_exists => {551 return Err(<CommonError<T>>::NoPermission.into());552 }553554 PropertyPermission {555 collection_admin,556 token_owner,557 ..558 } => {559 560 let is_token_create =561 is_token_create && (collection_admin || token_owner) && value.is_some();562 if !(is_token_create563 || (collection_admin && is_collection_admin())564 || (token_owner && is_token_owner()?))565 {566 fail!(<CommonError<T>>::NoPermission);567 }568 }569 }570571 match value {572 Some(value) => {573 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {574 properties.try_set(key.clone(), value)575 })576 .map_err(<CommonError<T>>::from)?;577578 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(579 collection.id,580 token_id,581 key,582 ));583 }584 None => {585 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {586 properties.remove(&key)587 })588 .map_err(<CommonError<T>>::from)?;589590 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(591 collection.id,592 token_id,593 key,594 ));595 }596 }597 }598599 Ok(())600 }601602 pub fn set_token_properties(603 collection: &RefungibleHandle<T>,604 sender: &T::CrossAccountId,605 token_id: TokenId,606 properties: impl Iterator<Item = Property>,607 is_token_create: bool,608 nesting_budget: &dyn Budget,609 ) -> DispatchResult {610 Self::modify_token_properties(611 collection,612 sender,613 token_id,614 properties.map(|p| (p.key, Some(p.value))),615 is_token_create,616 nesting_budget,617 )618 }619620 pub fn set_token_property(621 collection: &RefungibleHandle<T>,622 sender: &T::CrossAccountId,623 token_id: TokenId,624 property: Property,625 nesting_budget: &dyn Budget,626 ) -> DispatchResult {627 let is_token_create = false;628629 Self::set_token_properties(630 collection,631 sender,632 token_id,633 [property].into_iter(),634 is_token_create,635 nesting_budget,636 )637 }638639 pub fn delete_token_properties(640 collection: &RefungibleHandle<T>,641 sender: &T::CrossAccountId,642 token_id: TokenId,643 property_keys: impl Iterator<Item = PropertyKey>,644 nesting_budget: &dyn Budget,645 ) -> DispatchResult {646 let is_token_create = false;647648 Self::modify_token_properties(649 collection,650 sender,651 token_id,652 property_keys.into_iter().map(|key| (key, None)),653 is_token_create,654 nesting_budget,655 )656 }657658 pub fn delete_token_property(659 collection: &RefungibleHandle<T>,660 sender: &T::CrossAccountId,661 token_id: TokenId,662 property_key: PropertyKey,663 nesting_budget: &dyn Budget,664 ) -> DispatchResult {665 Self::delete_token_properties(666 collection,667 sender,668 token_id,669 [property_key].into_iter(),670 nesting_budget,671 )672 }673674 675 676 677 678 679 680 681 682 683 pub fn transfer(684 collection: &RefungibleHandle<T>,685 from: &T::CrossAccountId,686 to: &T::CrossAccountId,687 token: TokenId,688 amount: u128,689 nesting_budget: &dyn Budget,690 ) -> DispatchResult {691 ensure!(692 collection.limits.transfers_enabled(),693 <CommonError<T>>::TransferNotAllowed694 );695696 if collection.permissions.access() == AccessMode::AllowList {697 collection.check_allowlist(from)?;698 collection.check_allowlist(to)?;699 }700 <PalletCommon<T>>::ensure_correct_receiver(to)?;701702 let balance_from = <Balance<T>>::get((collection.id, token, from))703 .checked_sub(amount)704 .ok_or(<CommonError<T>>::TokenValueTooLow)?;705 let mut create_target = false;706 let from_to_differ = from != to;707 let balance_to = if from != to {708 let old_balance = <Balance<T>>::get((collection.id, token, to));709 if old_balance == 0 {710 create_target = true;711 }712 Some(713 old_balance714 .checked_add(amount)715 .ok_or(ArithmeticError::Overflow)?,716 )717 } else {718 None719 };720721 let account_balance_from = if balance_from == 0 {722 Some(723 <AccountBalance<T>>::get((collection.id, from))724 .checked_sub(1)725 726 .ok_or(ArithmeticError::Underflow)?,727 )728 } else {729 None730 };731 732 733 let account_balance_to = if create_target && from_to_differ {734 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))735 .checked_add(1)736 .ok_or(ArithmeticError::Overflow)?;737 ensure!(738 account_balance_to < collection.limits.account_token_ownership_limit(),739 <CommonError<T>>::AccountTokenLimitExceeded,740 );741742 Some(account_balance_to)743 } else {744 None745 };746747 748749 <PalletStructure<T>>::nest_if_sent_to_token(750 from.clone(),751 to,752 collection.id,753 token,754 nesting_budget,755 )?;756757 if let Some(balance_to) = balance_to {758 759 if balance_from == 0 {760 <Balance<T>>::remove((collection.id, token, from));761 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);762 } else {763 <Balance<T>>::insert((collection.id, token, from), balance_from);764 }765 <Balance<T>>::insert((collection.id, token, to), balance_to);766 if let Some(account_balance_from) = account_balance_from {767 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);768 <Owned<T>>::remove((collection.id, from, token));769 }770 if let Some(account_balance_to) = account_balance_to {771 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);772 <Owned<T>>::insert((collection.id, to, token), true);773 }774 }775776 <PalletEvm<T>>::deposit_log(777 ERC20Events::Transfer {778 from: *from.as_eth(),779 to: *to.as_eth(),780 value: amount.into(),781 }782 .to_log(T::EvmTokenAddressMapping::token_to_address(783 collection.id,784 token,785 )),786 );787788 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(789 collection.id,790 token,791 from.clone(),792 to.clone(),793 amount,794 ));795 Ok(())796 }797798 799 800 801 802 803 pub fn create_multiple_items(804 collection: &RefungibleHandle<T>,805 sender: &T::CrossAccountId,806 data: Vec<CreateItemData<T>>,807 nesting_budget: &dyn Budget,808 ) -> DispatchResult {809 if !collection.is_owner_or_admin(sender) {810 ensure!(811 collection.permissions.mint_mode(),812 <CommonError<T>>::PublicMintingNotAllowed813 );814 collection.check_allowlist(sender)?;815816 for item in data.iter() {817 for user in item.users.keys() {818 collection.check_allowlist(user)?;819 }820 }821 }822823 for item in data.iter() {824 for (owner, _) in item.users.iter() {825 <PalletCommon<T>>::ensure_correct_receiver(owner)?;826 }827 }828829 830 let totals = data831 .iter()832 .map(|data| {833 Ok(data834 .users835 .iter()836 .map(|u| u.1)837 .try_fold(0u128, |acc, v| acc.checked_add(*v))838 .ok_or(ArithmeticError::Overflow)?)839 })840 .collect::<Result<Vec<_>, DispatchError>>()?;841 for total in &totals {842 ensure!(843 *total <= MAX_REFUNGIBLE_PIECES,844 <Error<T>>::WrongRefungiblePieces845 );846 }847848 let first_token_id = <TokensMinted<T>>::get(collection.id);849 let tokens_minted = first_token_id850 .checked_add(data.len() as u32)851 .ok_or(ArithmeticError::Overflow)?;852 ensure!(853 tokens_minted < collection.limits.token_limit(),854 <CommonError<T>>::CollectionTokenLimitExceeded855 );856857 let mut balances = BTreeMap::new();858 for data in &data {859 for owner in data.users.keys() {860 let balance = balances861 .entry(owner)862 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));863 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;864865 ensure!(866 *balance <= collection.limits.account_token_ownership_limit(),867 <CommonError<T>>::AccountTokenLimitExceeded,868 );869 }870 }871872 for (i, token) in data.iter().enumerate() {873 let token_id = TokenId(first_token_id + i as u32 + 1);874 for (to, _) in token.users.iter() {875 <PalletStructure<T>>::check_nesting(876 sender.clone(),877 to,878 collection.id,879 token_id,880 nesting_budget,881 )?;882 }883 }884885 886887 with_transaction(|| {888 for (i, data) in data.iter().enumerate() {889 let token_id = first_token_id + i as u32 + 1;890 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);891892 <TokenData<T>>::insert(893 (collection.id, token_id),894 ItemData {895 const_data: data.const_data.clone(),896 },897 );898899 for (user, amount) in data.users.iter() {900 if *amount == 0 {901 continue;902 }903 <Balance<T>>::insert((collection.id, token_id, &user), amount);904 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);905 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(906 user,907 collection.id,908 TokenId(token_id),909 );910 }911912 if let Err(e) = Self::set_token_properties(913 collection,914 sender,915 TokenId(token_id),916 data.properties.clone().into_iter(),917 true,918 nesting_budget,919 ) {920 return TransactionOutcome::Rollback(Err(e));921 }922 }923 TransactionOutcome::Commit(Ok(()))924 })?;925926 <TokensMinted<T>>::insert(collection.id, tokens_minted);927928 for (account, balance) in balances {929 <AccountBalance<T>>::insert((collection.id, account), balance);930 }931932 for (i, token) in data.into_iter().enumerate() {933 let token_id = first_token_id + i as u32 + 1;934935 for (user, amount) in token.users.into_iter() {936 if amount == 0 {937 continue;938 }939940 <PalletEvm<T>>::deposit_log(941 ERC20Events::Transfer {942 from: H160::default(),943 to: *user.as_eth(),944 value: amount.into(),945 }946 .to_log(T::EvmTokenAddressMapping::token_to_address(947 collection.id,948 TokenId(token_id),949 )),950 );951 <PalletEvm<T>>::deposit_log(952 ERC721Events::Transfer {953 from: H160::default(),954 to: *user.as_eth(),955 token_id: token_id.into(),956 }957 .to_log(collection_id_to_address(collection.id)),958 );959 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(960 collection.id,961 TokenId(token_id),962 user,963 amount,964 ));965 }966 }967 Ok(())968 }969970 pub fn set_allowance_unchecked(971 collection: &RefungibleHandle<T>,972 sender: &T::CrossAccountId,973 spender: &T::CrossAccountId,974 token: TokenId,975 amount: u128,976 ) {977 if amount == 0 {978 <Allowance<T>>::remove((collection.id, token, sender, spender));979 } else {980 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);981 }982983 <PalletEvm<T>>::deposit_log(984 ERC20Events::Approval {985 owner: *sender.as_eth(),986 spender: *spender.as_eth(),987 value: amount.into(),988 }989 .to_log(T::EvmTokenAddressMapping::token_to_address(990 collection.id,991 token,992 )),993 );994 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(995 collection.id,996 token,997 sender.clone(),998 spender.clone(),999 amount,1000 ))1001 }10021003 1004 1005 1006 pub fn set_allowance(1007 collection: &RefungibleHandle<T>,1008 sender: &T::CrossAccountId,1009 spender: &T::CrossAccountId,1010 token: TokenId,1011 amount: u128,1012 ) -> DispatchResult {1013 if collection.permissions.access() == AccessMode::AllowList {1014 collection.check_allowlist(sender)?;1015 collection.check_allowlist(spender)?;1016 }10171018 <PalletCommon<T>>::ensure_correct_receiver(spender)?;10191020 if <Balance<T>>::get((collection.id, token, sender)) < amount {1021 ensure!(1022 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1023 <CommonError<T>>::CantApproveMoreThanOwned1024 );1025 }10261027 10281029 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1030 Ok(())1031 }10321033 1034 fn check_allowed(1035 collection: &RefungibleHandle<T>,1036 spender: &T::CrossAccountId,1037 from: &T::CrossAccountId,1038 token: TokenId,1039 amount: u128,1040 nesting_budget: &dyn Budget,1041 ) -> Result<Option<u128>, DispatchError> {1042 if spender.conv_eq(from) {1043 return Ok(None);1044 }1045 if collection.permissions.access() == AccessMode::AllowList {1046 1047 collection.check_allowlist(spender)?;1048 }1049 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1050 1051 ensure!(1052 <PalletStructure<T>>::check_indirectly_owned(1053 spender.clone(),1054 source.0,1055 source.1,1056 None,1057 nesting_budget1058 )?,1059 <CommonError<T>>::ApprovedValueTooLow,1060 );1061 return Ok(None);1062 }1063 let allowance =1064 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);1065 if allowance.is_none() {1066 ensure!(1067 collection.ignores_allowance(spender),1068 <CommonError<T>>::ApprovedValueTooLow1069 );1070 }1071 Ok(allowance)1072 }10731074 1075 1076 1077 1078 1079 1080 pub fn transfer_from(1081 collection: &RefungibleHandle<T>,1082 spender: &T::CrossAccountId,1083 from: &T::CrossAccountId,1084 to: &T::CrossAccountId,1085 token: TokenId,1086 amount: u128,1087 nesting_budget: &dyn Budget,1088 ) -> DispatchResult {1089 let allowance =1090 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;10911092 10931094 Self::transfer(collection, from, to, token, amount, nesting_budget)?;1095 if let Some(allowance) = allowance {1096 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1097 }1098 Ok(())1099 }11001101 1102 1103 1104 1105 1106 1107 pub fn burn_from(1108 collection: &RefungibleHandle<T>,1109 spender: &T::CrossAccountId,1110 from: &T::CrossAccountId,1111 token: TokenId,1112 amount: u128,1113 nesting_budget: &dyn Budget,1114 ) -> DispatchResult {1115 let allowance =1116 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11171118 11191120 Self::burn(collection, from, token, amount)?;1121 if let Some(allowance) = allowance {1122 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1123 }1124 Ok(())1125 }11261127 1128 1129 1130 1131 1132 1133 1134 pub fn create_item(1135 collection: &RefungibleHandle<T>,1136 sender: &T::CrossAccountId,1137 data: CreateItemData<T>,1138 nesting_budget: &dyn Budget,1139 ) -> DispatchResult {1140 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1141 }11421143 1144 1145 1146 1147 1148 1149 1150 pub fn repartition(1151 collection: &RefungibleHandle<T>,1152 owner: &T::CrossAccountId,1153 token: TokenId,1154 amount: u128,1155 ) -> DispatchResult {1156 ensure!(1157 amount <= MAX_REFUNGIBLE_PIECES,1158 <Error<T>>::WrongRefungiblePieces1159 );1160 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1161 1162 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1163 let balance = <Balance<T>>::get((collection.id, token, owner));1164 ensure!(1165 total_pieces == balance,1166 <Error<T>>::RepartitionWhileNotOwningAllPieces1167 );11681169 <Balance<T>>::insert((collection.id, token, owner), amount);1170 <TotalSupply<T>>::insert((collection.id, token), amount);11711172 if amount > total_pieces {1173 let mint_amount = amount - total_pieces;1174 <PalletEvm<T>>::deposit_log(1175 ERC20Events::Transfer {1176 from: H160::default(),1177 to: *owner.as_eth(),1178 value: mint_amount.into(),1179 }1180 .to_log(T::EvmTokenAddressMapping::token_to_address(1181 collection.id,1182 token,1183 )),1184 );1185 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1186 collection.id,1187 token,1188 owner.clone(),1189 mint_amount,1190 ));1191 } else if total_pieces > amount {1192 let burn_amount = total_pieces - amount;1193 <PalletEvm<T>>::deposit_log(1194 ERC20Events::Transfer {1195 from: *owner.as_eth(),1196 to: H160::default(),1197 value: burn_amount.into(),1198 }1199 .to_log(T::EvmTokenAddressMapping::token_to_address(1200 collection.id,1201 token,1202 )),1203 );1204 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1205 collection.id,1206 token,1207 owner.clone(),1208 burn_amount,1209 ));1210 }12111212 Ok(())1213 }12141215 fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1216 let mut owner = None;1217 let mut count = 0;1218 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1219 count += 1;1220 if count > 1 {1221 return None;1222 }1223 owner = Some(key);1224 }1225 owner1226 }12271228 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1229 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1230 }12311232 pub fn set_collection_properties(1233 collection: &RefungibleHandle<T>,1234 sender: &T::CrossAccountId,1235 properties: Vec<Property>,1236 ) -> DispatchResult {1237 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)1238 }12391240 pub fn delete_collection_properties(1241 collection: &RefungibleHandle<T>,1242 sender: &T::CrossAccountId,1243 property_keys: Vec<PropertyKey>,1244 ) -> DispatchResult {1245 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1246 }12471248 pub fn set_token_property_permissions(1249 collection: &RefungibleHandle<T>,1250 sender: &T::CrossAccountId,1251 property_permissions: Vec<PropertyKeyPermission>,1252 ) -> DispatchResult {1253 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1254 }12551256 1257 1258 1259 1260 1261 1262 pub fn token_owners(1263 collection_id: CollectionId,1264 token: TokenId,1265 ) -> Option<Vec<T::CrossAccountId>> {1266 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1267 .map(|(owner, _amount)| owner)1268 .take(10)1269 .collect();12701271 if res.is_empty() {1272 None1273 } else {1274 Some(res)1275 }1276 }1277}