12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788#![cfg_attr(not(feature = "std"), no_std)]8990use crate::erc20::ERC20Events;9192use codec::{Encode, Decode, MaxEncodedLen};93use core::ops::Deref;94use evm_coder::ToLog;95use frame_support::{BoundedVec, ensure, fail, storage::with_transaction, transactional};96use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};97use pallet_evm_coder_substrate::WithRecorder;98use pallet_common::{CommonCollectionOperations, Error as CommonError, Event as CommonEvent, Pallet as PalletCommon};99use pallet_structure::Pallet as PalletStructure;100use scale_info::TypeInfo;101use sp_core::H160;102use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};103use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};104use up_data_structs::{105 AccessMode, budget::Budget, CollectionId, CreateCollectionData, CreateRefungibleExData, CustomDataLimit, mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, TokenId,106 Property, PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue, TrySetProperty107};108109pub use pallet::*;110#[cfg(feature = "runtime-benchmarks")]111pub mod benchmarking;112pub mod common;113pub mod erc20;114pub mod erc721;115pub mod weights;116pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;117118#[struct_versioning::versioned(version = 2, upper)]119#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]120pub struct ItemData {121 pub const_data: BoundedVec<u8, CustomDataLimit>,122123 #[version(..2)]124 pub variable_data: BoundedVec<u8, CustomDataLimit>,125}126127#[frame_support::pallet]128pub mod pallet {129 use super::*;130 use frame_support::{131 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,132 traits::StorageVersion,133 };134 use frame_system::pallet_prelude::*;135 use up_data_structs::{CollectionId, TokenId};136 use super::weights::WeightInfo;137138 #[pallet::error]139 pub enum Error<T> {140 141 NotRefungibleDataUsedToMintFungibleCollectionToken,142 143 WrongRefungiblePieces,144 145 RepartitionWhileNotOwningAllPieces,146 147 RefungibleDisallowsNesting,148 149 SettingPropertiesNotAllowed,150 }151152 #[pallet::config]153 pub trait Config:154 frame_system::Config + pallet_common::Config + pallet_structure::Config155 {156 type WeightInfo: WeightInfo;157 }158159 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);160161 #[pallet::pallet]162 #[pallet::storage_version(STORAGE_VERSION)]163 #[pallet::generate_store(pub(super) trait Store)]164 pub struct Pallet<T>(_);165166 167 #[pallet::storage]168 pub type TokensMinted<T: Config> =169 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;170171 172 #[pallet::storage]173 pub type TokensBurnt<T: Config> =174 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;175176 177 #[pallet::storage]178 pub type TokenData<T: Config> = StorageNMap<179 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),180 Value = ItemData,181 QueryKind = ValueQuery,182 >;183184 #[pallet::storage]185 #[pallet::getter(fn token_properties)]186 pub type TokenProperties<T: Config> = StorageNMap<187 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),188 Value = up_data_structs::Properties,189 QueryKind = ValueQuery,190 OnEmpty = up_data_structs::TokenProperties,191 >;192193 194 #[pallet::storage]195 pub type TotalSupply<T: Config> = StorageNMap<196 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),197 Value = u128,198 QueryKind = ValueQuery,199 >;200201 202 #[pallet::storage]203 pub type Owned<T: Config> = StorageNMap<204 Key = (205 Key<Twox64Concat, CollectionId>,206 Key<Blake2_128Concat, T::CrossAccountId>,207 Key<Twox64Concat, TokenId>,208 ),209 Value = bool,210 QueryKind = ValueQuery,211 >;212213 214 #[pallet::storage]215 pub type AccountBalance<T: Config> = StorageNMap<216 Key = (217 Key<Twox64Concat, CollectionId>,218 219 Key<Blake2_128Concat, T::CrossAccountId>,220 ),221 Value = u32,222 QueryKind = ValueQuery,223 >;224225 226 #[pallet::storage]227 pub type Balance<T: Config> = StorageNMap<228 Key = (229 Key<Twox64Concat, CollectionId>,230 Key<Twox64Concat, TokenId>,231 232 Key<Blake2_128Concat, T::CrossAccountId>,233 ),234 Value = u128,235 QueryKind = ValueQuery,236 >;237238 239 #[pallet::storage]240 pub type Allowance<T: Config> = StorageNMap<241 Key = (242 Key<Twox64Concat, CollectionId>,243 Key<Twox64Concat, TokenId>,244 245 Key<Blake2_128, T::CrossAccountId>,246 247 Key<Blake2_128Concat, T::CrossAccountId>,248 ),249 Value = u128,250 QueryKind = ValueQuery,251 >;252253 #[pallet::hooks]254 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {255 fn on_runtime_upgrade() -> Weight {256 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {257 <TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {258 Some(<ItemDataVersion2>::from(v))259 })260 }261262 0263 }264 }265}266267pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);268impl<T: Config> RefungibleHandle<T> {269 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {270 Self(inner)271 }272 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {273 self.0274 }275 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {276 &mut self.0277 }278}279280impl<T: Config> Deref for RefungibleHandle<T> {281 type Target = pallet_common::CollectionHandle<T>;282283 fn deref(&self) -> &Self::Target {284 &self.0285 }286}287288impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {289 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {290 self.0.recorder()291 }292 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {293 self.0.into_recorder()294 }295}296297impl<T: Config> Pallet<T> {298 299 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {300 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)301 }302303 304 305 306 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {307 <TotalSupply<T>>::contains_key((collection.id, token))308 }309310 pub fn set_scoped_token_property(311 collection_id: CollectionId,312 token_id: TokenId,313 scope: PropertyScope,314 property: Property,315 ) -> DispatchResult {316 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {317 properties.try_scoped_set(scope, property.key, property.value)318 })319 .map_err(<CommonError<T>>::from)?;320321 Ok(())322 }323324 pub fn set_scoped_token_properties(325 collection_id: CollectionId,326 token_id: TokenId,327 scope: PropertyScope,328 properties: impl Iterator<Item = Property>,329 ) -> DispatchResult {330 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {331 stored_properties.try_scoped_set_from_iter(scope, properties)332 })333 .map_err(<CommonError<T>>::from)?;334335 Ok(())336 }337}338339340impl<T: Config> Pallet<T> {341 342 343 344 345 346 pub fn init_collection(347 owner: T::CrossAccountId,348 data: CreateCollectionData<T::AccountId>,349 ) -> Result<CollectionId, DispatchError> {350 <PalletCommon<T>>::init_collection(owner, data, false)351 }352353 354 355 356 357 pub fn destroy_collection(358 collection: RefungibleHandle<T>,359 sender: &T::CrossAccountId,360 ) -> DispatchResult {361 let id = collection.id;362363 if Self::collection_has_tokens(id) {364 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());365 }366367 368369 PalletCommon::destroy_collection(collection.0, sender)?;370371 <TokensMinted<T>>::remove(id);372 <TokensBurnt<T>>::remove(id);373 <TokenData<T>>::remove_prefix((id,), None);374 <TotalSupply<T>>::remove_prefix((id,), None);375 <Balance<T>>::remove_prefix((id,), None);376 <Allowance<T>>::remove_prefix((id,), None);377 <Owned<T>>::remove_prefix((id,), None);378 <AccountBalance<T>>::remove_prefix((id,), None);379 Ok(())380 }381382 fn collection_has_tokens(collection_id: CollectionId) -> bool {383 <TokenData<T>>::iter_prefix((collection_id,))384 .next()385 .is_some()386 }387388 pub fn burn_token_unchecked(389 collection: &RefungibleHandle<T>,390 token_id: TokenId,391 ) -> DispatchResult {392 let burnt = <TokensBurnt<T>>::get(collection.id)393 .checked_add(1)394 .ok_or(ArithmeticError::Overflow)?;395396 <TokensBurnt<T>>::insert(collection.id, burnt);397 <TokenData<T>>::remove((collection.id, token_id));398 <TokenProperties<T>>::remove((collection.id, token_id));399 <TotalSupply<T>>::remove((collection.id, token_id));400 <Balance<T>>::remove_prefix((collection.id, token_id), None);401 <Allowance<T>>::remove_prefix((collection.id, token_id), None);402 403 Ok(())404 }405406 407 408 409 410 411 412 413 414 415 416 417 pub fn burn(418 collection: &RefungibleHandle<T>,419 owner: &T::CrossAccountId,420 token: TokenId,421 amount: u128,422 ) -> DispatchResult {423 let total_supply = <TotalSupply<T>>::get((collection.id, token))424 .checked_sub(amount)425 .ok_or(<CommonError<T>>::TokenValueTooLow)?;426427 428 if total_supply == 0 {429 430 ensure!(431 <Balance<T>>::get((collection.id, token, owner)) == amount,432 <CommonError<T>>::TokenValueTooLow433 );434 let account_balance = <AccountBalance<T>>::get((collection.id, owner))435 .checked_sub(1)436 437 .ok_or(ArithmeticError::Underflow)?;438439 440441 <Owned<T>>::remove((collection.id, owner, token));442 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);443 <AccountBalance<T>>::insert((collection.id, owner), account_balance);444 Self::burn_token_unchecked(collection, token)?;445 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(446 collection.id,447 token,448 owner.clone(),449 amount,450 ));451 return Ok(());452 }453454 let balance = <Balance<T>>::get((collection.id, token, owner))455 .checked_sub(amount)456 .ok_or(<CommonError<T>>::TokenValueTooLow)?;457 let account_balance = if balance == 0 {458 <AccountBalance<T>>::get((collection.id, owner))459 .checked_sub(1)460 461 .ok_or(ArithmeticError::Underflow)?462 } else {463 0464 };465466 467468 if balance == 0 {469 <Owned<T>>::remove((collection.id, owner, token));470 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);471 <Balance<T>>::remove((collection.id, token, owner));472 <AccountBalance<T>>::insert((collection.id, owner), account_balance);473 } else {474 <Balance<T>>::insert((collection.id, token, owner), balance);475 }476 <TotalSupply<T>>::insert((collection.id, token), total_supply);477478 <PalletEvm<T>>::deposit_log(479 ERC20Events::Transfer {480 from: *owner.as_eth(),481 to: H160::default(),482 value: amount.into(),483 }484 .to_log(T::EvmTokenAddressMapping::token_to_address(485 collection.id,486 token,487 )),488 );489 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(490 collection.id,491 token,492 owner.clone(),493 amount,494 ));495 Ok(())496 }497498 #[transactional]499 fn modify_token_properties(500 collection: &RefungibleHandle<T>,501 sender: &T::CrossAccountId,502 token_id: TokenId,503 properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,504 is_token_create: bool,505 nesting_budget: &dyn Budget,506 ) -> DispatchResult {507 let is_collection_admin = || collection.is_owner_or_admin(sender);508 let is_token_owner = || -> Result<bool, DispatchError> {509 let balance = collection.balance(sender.clone(), token_id);510 let total_pieces: u128 =511 Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);512 if balance != total_pieces {513 return Ok(false);514 }515516 let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(517 sender.clone(),518 collection.id,519 token_id,520 None,521 nesting_budget,522 )?;523524 Ok(is_bundle_owner)525 };526527 for (key, value) in properties {528 let permission = <PalletCommon<T>>::property_permissions(collection.id)529 .get(&key)530 .cloned()531 .unwrap_or_else(PropertyPermission::none);532533 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))534 .get(&key)535 .is_some();536537 match permission {538 PropertyPermission { mutable: false, .. } if is_property_exists => {539 return Err(<CommonError<T>>::NoPermission.into());540 }541542 PropertyPermission {543 collection_admin,544 token_owner,545 ..546 } => {547 548 let is_token_create =549 is_token_create && (collection_admin || token_owner) && value.is_some();550 if !(is_token_create551 || (collection_admin && is_collection_admin())552 || (token_owner && is_token_owner()?))553 {554 fail!(<CommonError<T>>::NoPermission);555 }556 }557 }558559 match value {560 Some(value) => {561 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {562 properties.try_set(key.clone(), value)563 })564 .map_err(<CommonError<T>>::from)?;565566 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(567 collection.id,568 token_id,569 key,570 ));571 }572 None => {573 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {574 properties.remove(&key)575 })576 .map_err(<CommonError<T>>::from)?;577578 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(579 collection.id,580 token_id,581 key,582 ));583 }584 }585 }586587 Ok(())588 }589590 pub fn set_token_properties(591 collection: &RefungibleHandle<T>,592 sender: &T::CrossAccountId,593 token_id: TokenId,594 properties: impl Iterator<Item = Property>,595 is_token_create: bool,596 nesting_budget: &dyn Budget,597 ) -> DispatchResult {598 Self::modify_token_properties(599 collection,600 sender,601 token_id,602 properties.map(|p| (p.key, Some(p.value))),603 is_token_create,604 nesting_budget,605 )606 }607608 pub fn set_token_property(609 collection: &RefungibleHandle<T>,610 sender: &T::CrossAccountId,611 token_id: TokenId,612 property: Property,613 nesting_budget: &dyn Budget,614 ) -> DispatchResult {615 let is_token_create = false;616617 Self::set_token_properties(618 collection,619 sender,620 token_id,621 [property].into_iter(),622 is_token_create,623 nesting_budget,624 )625 }626627 pub fn delete_token_properties(628 collection: &RefungibleHandle<T>,629 sender: &T::CrossAccountId,630 token_id: TokenId,631 property_keys: impl Iterator<Item = PropertyKey>,632 nesting_budget: &dyn Budget,633 ) -> DispatchResult {634 let is_token_create = false;635636 Self::modify_token_properties(637 collection,638 sender,639 token_id,640 property_keys.into_iter().map(|key| (key, None)),641 is_token_create,642 nesting_budget,643 )644 }645646 pub fn delete_token_property(647 collection: &RefungibleHandle<T>,648 sender: &T::CrossAccountId,649 token_id: TokenId,650 property_key: PropertyKey,651 nesting_budget: &dyn Budget,652 ) -> DispatchResult {653 Self::delete_token_properties(654 collection,655 sender,656 token_id,657 [property_key].into_iter(),658 nesting_budget,659 )660 }661662 663 664 665 666 667 668 669 670 671 pub fn transfer(672 collection: &RefungibleHandle<T>,673 from: &T::CrossAccountId,674 to: &T::CrossAccountId,675 token: TokenId,676 amount: u128,677 nesting_budget: &dyn Budget,678 ) -> DispatchResult {679 ensure!(680 collection.limits.transfers_enabled(),681 <CommonError<T>>::TransferNotAllowed682 );683684 if collection.permissions.access() == AccessMode::AllowList {685 collection.check_allowlist(from)?;686 collection.check_allowlist(to)?;687 }688 <PalletCommon<T>>::ensure_correct_receiver(to)?;689690 let balance_from = <Balance<T>>::get((collection.id, token, from))691 .checked_sub(amount)692 .ok_or(<CommonError<T>>::TokenValueTooLow)?;693 let mut create_target = false;694 let from_to_differ = from != to;695 let balance_to = if from != to {696 let old_balance = <Balance<T>>::get((collection.id, token, to));697 if old_balance == 0 {698 create_target = true;699 }700 Some(701 old_balance702 .checked_add(amount)703 .ok_or(ArithmeticError::Overflow)?,704 )705 } else {706 None707 };708709 let account_balance_from = if balance_from == 0 {710 Some(711 <AccountBalance<T>>::get((collection.id, from))712 .checked_sub(1)713 714 .ok_or(ArithmeticError::Underflow)?,715 )716 } else {717 None718 };719 720 721 let account_balance_to = if create_target && from_to_differ {722 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))723 .checked_add(1)724 .ok_or(ArithmeticError::Overflow)?;725 ensure!(726 account_balance_to < collection.limits.account_token_ownership_limit(),727 <CommonError<T>>::AccountTokenLimitExceeded,728 );729730 Some(account_balance_to)731 } else {732 None733 };734735 736737 <PalletStructure<T>>::nest_if_sent_to_token(738 from.clone(),739 to,740 collection.id,741 token,742 nesting_budget,743 )?;744745 if let Some(balance_to) = balance_to {746 747 if balance_from == 0 {748 <Balance<T>>::remove((collection.id, token, from));749 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);750 } else {751 <Balance<T>>::insert((collection.id, token, from), balance_from);752 }753 <Balance<T>>::insert((collection.id, token, to), balance_to);754 if let Some(account_balance_from) = account_balance_from {755 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);756 <Owned<T>>::remove((collection.id, from, token));757 }758 if let Some(account_balance_to) = account_balance_to {759 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);760 <Owned<T>>::insert((collection.id, to, token), true);761 }762 }763764 <PalletEvm<T>>::deposit_log(765 ERC20Events::Transfer {766 from: *from.as_eth(),767 to: *to.as_eth(),768 value: amount.into(),769 }770 .to_log(T::EvmTokenAddressMapping::token_to_address(771 collection.id,772 token,773 )),774 );775 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(776 collection.id,777 token,778 from.clone(),779 to.clone(),780 amount,781 ));782 Ok(())783 }784785 786 787 788 789 790 pub fn create_multiple_items(791 collection: &RefungibleHandle<T>,792 sender: &T::CrossAccountId,793 data: Vec<CreateRefungibleExData<T::CrossAccountId>>,794 nesting_budget: &dyn Budget,795 ) -> DispatchResult {796 if !collection.is_owner_or_admin(sender) {797 ensure!(798 collection.permissions.mint_mode(),799 <CommonError<T>>::PublicMintingNotAllowed800 );801 collection.check_allowlist(sender)?;802803 for item in data.iter() {804 for user in item.users.keys() {805 collection.check_allowlist(user)?;806 }807 }808 }809810 for item in data.iter() {811 for (owner, _) in item.users.iter() {812 <PalletCommon<T>>::ensure_correct_receiver(owner)?;813 }814 }815816 817 let totals = data818 .iter()819 .map(|data| {820 Ok(data821 .users822 .iter()823 .map(|u| u.1)824 .try_fold(0u128, |acc, v| acc.checked_add(*v))825 .ok_or(ArithmeticError::Overflow)?)826 })827 .collect::<Result<Vec<_>, DispatchError>>()?;828 for total in &totals {829 ensure!(830 *total <= MAX_REFUNGIBLE_PIECES,831 <Error<T>>::WrongRefungiblePieces832 );833 }834835 let first_token_id = <TokensMinted<T>>::get(collection.id);836 let tokens_minted = first_token_id837 .checked_add(data.len() as u32)838 .ok_or(ArithmeticError::Overflow)?;839 ensure!(840 tokens_minted < collection.limits.token_limit(),841 <CommonError<T>>::CollectionTokenLimitExceeded842 );843844 let mut balances = BTreeMap::new();845 for data in &data {846 for owner in data.users.keys() {847 let balance = balances848 .entry(owner)849 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));850 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;851852 ensure!(853 *balance <= collection.limits.account_token_ownership_limit(),854 <CommonError<T>>::AccountTokenLimitExceeded,855 );856 }857 }858859 for (i, token) in data.iter().enumerate() {860 let token_id = TokenId(first_token_id + i as u32 + 1);861 for (to, _) in token.users.iter() {862 <PalletStructure<T>>::check_nesting(863 sender.clone(),864 to,865 collection.id,866 token_id,867 nesting_budget,868 )?;869 }870 }871872 873874 with_transaction(|| {875 for (i, data) in data.iter().enumerate() {876 let token_id = first_token_id + i as u32 + 1;877 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);878879 <TokenData<T>>::insert(880 (collection.id, token_id),881 ItemData {882 const_data: data.const_data.clone(),883 },884 );885886 for (user, amount) in data.users.iter() {887 if *amount == 0 {888 continue;889 }890 <Balance<T>>::insert((collection.id, token_id, &user), amount);891 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);892 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(893 user,894 collection.id,895 TokenId(token_id),896 );897 }898899 if let Err(e) = Self::set_token_properties(900 collection,901 sender,902 TokenId(token_id),903 data.properties.clone().into_iter(),904 true,905 nesting_budget,906 ) {907 return TransactionOutcome::Rollback(Err(e));908 }909 }910 TransactionOutcome::Commit(Ok(()))911 })?;912913 <TokensMinted<T>>::insert(collection.id, tokens_minted);914915 for (account, balance) in balances {916 <AccountBalance<T>>::insert((collection.id, account), balance);917 }918919 for (i, token) in data.into_iter().enumerate() {920 let token_id = first_token_id + i as u32 + 1;921922 for (user, amount) in token.users.into_iter() {923 if amount == 0 {924 continue;925 }926927 <PalletEvm<T>>::deposit_log(928 ERC20Events::Transfer {929 from: H160::default(),930 to: *user.as_eth(),931 value: amount.into(),932 }933 .to_log(T::EvmTokenAddressMapping::token_to_address(934 collection.id,935 TokenId(token_id),936 )),937 );938 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(939 collection.id,940 TokenId(token_id),941 user,942 amount,943 ));944 }945 }946 Ok(())947 }948949 pub fn set_allowance_unchecked(950 collection: &RefungibleHandle<T>,951 sender: &T::CrossAccountId,952 spender: &T::CrossAccountId,953 token: TokenId,954 amount: u128,955 ) {956 if amount == 0 {957 <Allowance<T>>::remove((collection.id, token, sender, spender));958 } else {959 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);960 }961962 <PalletEvm<T>>::deposit_log(963 ERC20Events::Approval {964 owner: *sender.as_eth(),965 spender: *spender.as_eth(),966 value: amount.into(),967 }968 .to_log(T::EvmTokenAddressMapping::token_to_address(969 collection.id,970 token,971 )),972 );973 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(974 collection.id,975 token,976 sender.clone(),977 spender.clone(),978 amount,979 ))980 }981982 983 984 985 pub fn set_allowance(986 collection: &RefungibleHandle<T>,987 sender: &T::CrossAccountId,988 spender: &T::CrossAccountId,989 token: TokenId,990 amount: u128,991 ) -> DispatchResult {992 if collection.permissions.access() == AccessMode::AllowList {993 collection.check_allowlist(sender)?;994 collection.check_allowlist(spender)?;995 }996997 <PalletCommon<T>>::ensure_correct_receiver(spender)?;998999 if <Balance<T>>::get((collection.id, token, sender)) < amount {1000 ensure!(1001 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1002 <CommonError<T>>::CantApproveMoreThanOwned1003 );1004 }10051006 10071008 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1009 Ok(())1010 }10111012 1013 fn check_allowed(1014 collection: &RefungibleHandle<T>,1015 spender: &T::CrossAccountId,1016 from: &T::CrossAccountId,1017 token: TokenId,1018 amount: u128,1019 nesting_budget: &dyn Budget,1020 ) -> Result<Option<u128>, DispatchError> {1021 if spender.conv_eq(from) {1022 return Ok(None);1023 }1024 if collection.permissions.access() == AccessMode::AllowList {1025 1026 collection.check_allowlist(spender)?;1027 }1028 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1029 1030 ensure!(1031 <PalletStructure<T>>::check_indirectly_owned(1032 spender.clone(),1033 source.0,1034 source.1,1035 None,1036 nesting_budget1037 )?,1038 <CommonError<T>>::ApprovedValueTooLow,1039 );1040 return Ok(None);1041 }1042 let allowance =1043 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);1044 if allowance.is_none() {1045 ensure!(1046 collection.ignores_allowance(spender),1047 <CommonError<T>>::ApprovedValueTooLow1048 );1049 }1050 Ok(allowance)1051 }10521053 1054 1055 1056 1057 1058 1059 pub fn transfer_from(1060 collection: &RefungibleHandle<T>,1061 spender: &T::CrossAccountId,1062 from: &T::CrossAccountId,1063 to: &T::CrossAccountId,1064 token: TokenId,1065 amount: u128,1066 nesting_budget: &dyn Budget,1067 ) -> DispatchResult {1068 let allowance =1069 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;10701071 10721073 Self::transfer(collection, from, to, token, amount, nesting_budget)?;1074 if let Some(allowance) = allowance {1075 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1076 }1077 Ok(())1078 }10791080 1081 1082 1083 1084 1085 1086 pub fn burn_from(1087 collection: &RefungibleHandle<T>,1088 spender: &T::CrossAccountId,1089 from: &T::CrossAccountId,1090 token: TokenId,1091 amount: u128,1092 nesting_budget: &dyn Budget,1093 ) -> DispatchResult {1094 let allowance =1095 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;10961097 10981099 Self::burn(collection, from, token, amount)?;1100 if let Some(allowance) = allowance {1101 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1102 }1103 Ok(())1104 }11051106 1107 1108 1109 1110 1111 1112 1113 pub fn create_item(1114 collection: &RefungibleHandle<T>,1115 sender: &T::CrossAccountId,1116 data: CreateRefungibleExData<T::CrossAccountId>,1117 nesting_budget: &dyn Budget,1118 ) -> DispatchResult {1119 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1120 }11211122 1123 1124 1125 1126 1127 1128 1129 pub fn repartition(1130 collection: &RefungibleHandle<T>,1131 owner: &T::CrossAccountId,1132 token: TokenId,1133 amount: u128,1134 ) -> DispatchResult {1135 ensure!(1136 amount <= MAX_REFUNGIBLE_PIECES,1137 <Error<T>>::WrongRefungiblePieces1138 );1139 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1140 1141 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1142 let balance = <Balance<T>>::get((collection.id, token, owner));1143 ensure!(1144 total_pieces == balance,1145 <Error<T>>::RepartitionWhileNotOwningAllPieces1146 );11471148 <Balance<T>>::insert((collection.id, token, owner), amount);1149 <TotalSupply<T>>::insert((collection.id, token), amount);1150 Ok(())1151 }11521153 fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1154 let mut owner = None;1155 let mut count = 0;1156 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1157 count += 1;1158 if count > 1 {1159 return None;1160 }1161 owner = Some(key);1162 }1163 owner1164 }11651166 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1167 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1168 }11691170 pub fn set_collection_properties(1171 collection: &RefungibleHandle<T>,1172 sender: &T::CrossAccountId,1173 properties: Vec<Property>,1174 ) -> DispatchResult {1175 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)1176 }11771178 pub fn delete_collection_properties(1179 collection: &RefungibleHandle<T>,1180 sender: &T::CrossAccountId,1181 property_keys: Vec<PropertyKey>,1182 ) -> DispatchResult {1183 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1184 }11851186 pub fn set_token_property_permissions(1187 collection: &RefungibleHandle<T>,1188 sender: &T::CrossAccountId,1189 property_permissions: Vec<PropertyKeyPermission>,1190 ) -> DispatchResult {1191 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1192 }1193}