12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879#![cfg_attr(not(feature = "std"), no_std)]8081use core::ops::Deref;82use evm_coder::ToLog;83use frame_support::{84 ensure,85 pallet_prelude::{DispatchResultWithPostInfo, Pays},86 dispatch::PostDispatchInfo,87};88use pallet_evm::account::CrossAccountId;89use up_data_structs::{90 AccessMode, CollectionId, CollectionFlags, TokenId, CreateCollectionData,91 mapping::TokenAddressMapping, budget::Budget, PropertyKey, Property,92};93use pallet_common::{94 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,95 eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,96 weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info,97};98use pallet_evm::Pallet as PalletEvm;99use pallet_structure::Pallet as PalletStructure;100use pallet_evm_coder_substrate::WithRecorder;101use sp_core::H160;102use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};103use sp_std::{collections::btree_map::BTreeMap, vec::Vec};104use weights::WeightInfo;105pub use pallet::*;106107use crate::erc::ERC20Events;108#[cfg(feature = "runtime-benchmarks")]109pub mod benchmarking;110pub mod common;111pub mod erc;112pub mod weights;113114pub type CreateItemData<T> = (<T as pallet_evm::Config>::CrossAccountId, u128);115pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;116117#[frame_support::pallet]118pub mod pallet {119 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};120 use up_data_structs::CollectionId;121 use super::weights::WeightInfo;122123 #[pallet::error]124 pub enum Error<T> {125 126 NotFungibleDataUsedToMintFungibleCollectionToken,127 128 FungibleItemsHaveNoId,129 130 FungibleItemsDontHaveData,131 132 FungibleDisallowsNesting,133 134 SettingPropertiesNotAllowed,135 136 SettingAllowanceForAllNotAllowed,137 138 FungibleTokensAreAlwaysValid,139 }140141 #[pallet::config]142 pub trait Config:143 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config144 {145 type WeightInfo: WeightInfo;146 }147148 #[pallet::pallet]149 pub struct Pallet<T>(_);150151 152 #[pallet::storage]153 pub type TotalSupply<T: Config> =154 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;155156 157 #[pallet::storage]158 pub type Balance<T: Config> = StorageNMap<159 Key = (160 Key<Twox64Concat, CollectionId>,161 Key<Blake2_128Concat, T::CrossAccountId>,162 ),163 Value = u128,164 QueryKind = ValueQuery,165 >;166167 168 #[pallet::storage]169 pub type Allowance<T: Config> = StorageNMap<170 Key = (171 Key<Twox64Concat, CollectionId>,172 Key<Blake2_128, T::CrossAccountId>, 173 Key<Blake2_128Concat, T::CrossAccountId>, 174 ),175 Value = u128,176 QueryKind = ValueQuery,177 >;178}179180181182pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);183184185impl<T: Config> FungibleHandle<T> {186 187 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {188 Self(inner)189 }190191 192 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {193 self.0194 }195 196 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {197 &mut self.0198 }199}200impl<T: Config> WithRecorder<T> for FungibleHandle<T> {201 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {202 self.0.recorder()203 }204 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {205 self.0.into_recorder()206 }207}208impl<T: Config> Deref for FungibleHandle<T> {209 type Target = pallet_common::CollectionHandle<T>;210211 fn deref(&self) -> &Self::Target {212 &self.0213 }214}215216217impl<T: Config> Pallet<T> {218 219 pub fn init_collection(220 owner: T::CrossAccountId,221 payer: T::CrossAccountId,222 data: CreateCollectionData<T::AccountId>,223 flags: CollectionFlags,224 ) -> Result<CollectionId, DispatchError> {225 <PalletCommon<T>>::init_collection(owner, payer, data, flags)226 }227228 229 pub fn init_foreign_collection(230 owner: T::CrossAccountId,231 payer: T::CrossAccountId,232 data: CreateCollectionData<T::AccountId>,233 ) -> Result<CollectionId, DispatchError> {234 let id = <PalletCommon<T>>::init_collection(235 owner,236 payer,237 data,238 CollectionFlags {239 foreign: true,240 ..Default::default()241 },242 )?;243 Ok(id)244 }245246 247 pub fn destroy_collection(248 collection: FungibleHandle<T>,249 sender: &T::CrossAccountId,250 ) -> DispatchResult {251 let id = collection.id;252253 if Self::collection_has_tokens(id) {254 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());255 }256257 258259 PalletCommon::destroy_collection(collection.0, sender)?;260261 <TotalSupply<T>>::remove(id);262 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);263 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);264 Ok(())265 }266267 268 pub fn set_collection_properties(269 collection: &FungibleHandle<T>,270 sender: &T::CrossAccountId,271 properties: Vec<Property>,272 ) -> DispatchResult {273 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())274 }275276 277 pub fn delete_collection_properties(278 collection: &FungibleHandle<T>,279 sender: &T::CrossAccountId,280 property_keys: Vec<PropertyKey>,281 ) -> DispatchResult {282 <PalletCommon<T>>::delete_collection_properties(283 collection,284 sender,285 property_keys.into_iter(),286 )287 }288289 290 fn collection_has_tokens(collection_id: CollectionId) -> bool {291 <TotalSupply<T>>::get(collection_id) != 0292 }293294 295 296 297 pub fn burn(298 collection: &FungibleHandle<T>,299 owner: &T::CrossAccountId,300 amount: u128,301 ) -> DispatchResult {302 let total_supply = <TotalSupply<T>>::get(collection.id)303 .checked_sub(amount)304 .ok_or(<CommonError<T>>::TokenValueTooLow)?;305306 let balance = <Balance<T>>::get((collection.id, owner))307 .checked_sub(amount)308 .ok_or(<CommonError<T>>::TokenValueTooLow)?;309310 311 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);312313 if collection.permissions.access() == AccessMode::AllowList {314 collection.check_allowlist(owner)?;315 }316317 318319 if balance == 0 {320 <Balance<T>>::remove((collection.id, owner));321 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());322 } else {323 <Balance<T>>::insert((collection.id, owner), balance);324 }325 <TotalSupply<T>>::insert(collection.id, total_supply);326327 <PalletEvm<T>>::deposit_log(328 ERC20Events::Transfer {329 from: *owner.as_eth(),330 to: H160::default(),331 value: amount.into(),332 }333 .to_log(collection_id_to_address(collection.id)),334 );335 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(336 collection.id,337 TokenId::default(),338 owner.clone(),339 amount,340 ));341 Ok(())342 }343344 345 pub fn burn_foreign(346 collection: &FungibleHandle<T>,347 owner: &T::CrossAccountId,348 amount: u128,349 ) -> DispatchResult {350 let total_supply = <TotalSupply<T>>::get(collection.id)351 .checked_sub(amount)352 .ok_or(<CommonError<T>>::TokenValueTooLow)?;353354 let balance = <Balance<T>>::get((collection.id, owner))355 .checked_sub(amount)356 .ok_or(<CommonError<T>>::TokenValueTooLow)?;357 358359 if balance == 0 {360 <Balance<T>>::remove((collection.id, owner));361 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());362 } else {363 <Balance<T>>::insert((collection.id, owner), balance);364 }365 <TotalSupply<T>>::insert(collection.id, total_supply);366367 <PalletEvm<T>>::deposit_log(368 ERC20Events::Transfer {369 from: *owner.as_eth(),370 to: H160::default(),371 value: amount.into(),372 }373 .to_log(collection_id_to_address(collection.id)),374 );375 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(376 collection.id,377 TokenId::default(),378 owner.clone(),379 amount,380 ));381 Ok(())382 }383384 385 386 387 388 389 390 391 pub fn transfer(392 collection: &FungibleHandle<T>,393 from: &T::CrossAccountId,394 to: &T::CrossAccountId,395 amount: u128,396 nesting_budget: &dyn Budget,397 ) -> DispatchResultWithPostInfo {398 ensure!(399 collection.limits.transfers_enabled(),400 <CommonError<T>>::TransferNotAllowed,401 );402403 let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();404405 if collection.permissions.access() == AccessMode::AllowList {406 collection.check_allowlist(from)?;407 collection.check_allowlist(to)?;408 actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;409 }410 <PalletCommon<T>>::ensure_correct_receiver(to)?;411 let balance_from = <Balance<T>>::get((collection.id, from))412 .checked_sub(amount)413 .ok_or(<CommonError<T>>::TokenValueTooLow)?;414 let balance_to = if from != to && amount != 0 {415 Some(416 <Balance<T>>::get((collection.id, to))417 .checked_add(amount)418 .ok_or(ArithmeticError::Overflow)?,419 )420 } else {421 None422 };423424 425426 if let Some(balance_to) = balance_to {427 428429 <PalletStructure<T>>::nest_if_sent_to_token(430 from.clone(),431 to,432 collection.id,433 TokenId::default(),434 nesting_budget,435 )?;436437 if balance_from == 0 {438 <Balance<T>>::remove((collection.id, from));439 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());440 } else {441 <Balance<T>>::insert((collection.id, from), balance_from);442 }443 <Balance<T>>::insert((collection.id, to), balance_to);444 }445446 <PalletEvm<T>>::deposit_log(447 ERC20Events::Transfer {448 from: *from.as_eth(),449 to: *to.as_eth(),450 value: amount.into(),451 }452 .to_log(collection_id_to_address(collection.id)),453 );454 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(455 collection.id,456 TokenId::default(),457 from.clone(),458 to.clone(),459 amount,460 ));461462 Ok(PostDispatchInfo {463 actual_weight: Some(actual_weight),464 pays_fee: Pays::Yes,465 })466 }467468 469 470 471 pub fn create_multiple_items_common(472 collection: &FungibleHandle<T>,473 sender: &T::CrossAccountId,474 data: BTreeMap<T::CrossAccountId, u128>,475 nesting_budget: &dyn Budget,476 ) -> DispatchResult {477 let total_supply = data478 .values()479 .copied()480 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {481 acc.checked_add(v)482 })483 .ok_or(ArithmeticError::Overflow)?;484485 for (to, _) in data.iter() {486 <PalletStructure<T>>::check_nesting(487 sender.clone(),488 to,489 collection.id,490 TokenId::default(),491 nesting_budget,492 )?;493 }494495 let updated_balances = data496 .into_iter()497 .map(|(user, amount)| {498 let updated_balance = <Balance<T>>::get((collection.id, &user))499 .checked_add(amount)500 .ok_or(ArithmeticError::Overflow)?;501 Ok((user, amount, updated_balance))502 })503 .collect::<Result<Vec<_>, DispatchError>>()?;504505 506507 <TotalSupply<T>>::insert(collection.id, total_supply);508 for (user, amount, updated_balance) in updated_balances {509 <Balance<T>>::insert((collection.id, &user), updated_balance);510 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(511 &user,512 collection.id,513 TokenId::default(),514 );515 <PalletEvm<T>>::deposit_log(516 ERC20Events::Transfer {517 from: H160::default(),518 to: *user.as_eth(),519 value: amount.into(),520 }521 .to_log(collection_id_to_address(collection.id)),522 );523 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(524 collection.id,525 TokenId::default(),526 user.clone(),527 amount,528 ));529 }530531 Ok(())532 }533534 535 536 pub fn create_multiple_items(537 collection: &FungibleHandle<T>,538 sender: &T::CrossAccountId,539 data: BTreeMap<T::CrossAccountId, u128>,540 nesting_budget: &dyn Budget,541 ) -> DispatchResult {542 543 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);544545 if !collection.is_owner_or_admin(sender) {546 ensure!(547 collection.permissions.mint_mode(),548 <CommonError<T>>::PublicMintingNotAllowed549 );550 collection.check_allowlist(sender)?;551552 for (owner, _) in data.iter() {553 collection.check_allowlist(owner)?;554 }555 }556557 Self::create_multiple_items_common(collection, sender, data, nesting_budget)558 }559560 561 562 pub fn create_multiple_items_foreign(563 collection: &FungibleHandle<T>,564 sender: &T::CrossAccountId,565 data: BTreeMap<T::CrossAccountId, u128>,566 nesting_budget: &dyn Budget,567 ) -> DispatchResult {568 Self::create_multiple_items_common(collection, sender, data, nesting_budget)569 }570571 fn set_allowance_unchecked(572 collection: &FungibleHandle<T>,573 owner: &T::CrossAccountId,574 spender: &T::CrossAccountId,575 amount: u128,576 ) {577 if amount == 0 {578 <Allowance<T>>::remove((collection.id, owner, spender));579 } else {580 <Allowance<T>>::insert((collection.id, owner, spender), amount);581 }582583 <PalletEvm<T>>::deposit_log(584 ERC20Events::Approval {585 owner: *owner.as_eth(),586 spender: *spender.as_eth(),587 value: amount.into(),588 }589 .to_log(collection_id_to_address(collection.id)),590 );591 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(592 collection.id,593 TokenId(0),594 owner.clone(),595 spender.clone(),596 amount,597 ));598 }599600 601 602 603 604 605 606 pub fn set_allowance(607 collection: &FungibleHandle<T>,608 owner: &T::CrossAccountId,609 spender: &T::CrossAccountId,610 amount: u128,611 ) -> DispatchResult {612 if collection.permissions.access() == AccessMode::AllowList {613 collection.check_allowlist(owner)?;614 collection.check_allowlist(spender)?;615 }616617 if <Balance<T>>::get((collection.id, owner)) < amount {618 ensure!(619 collection.ignores_owned_amount(owner),620 <CommonError<T>>::CantApproveMoreThanOwned621 );622 }623624 625626 Self::set_allowance_unchecked(collection, owner, spender, amount);627 Ok(())628 }629630 631 632 633 634 635 636 637 pub fn set_allowance_from(638 collection: &FungibleHandle<T>,639 sender: &T::CrossAccountId,640 from: &T::CrossAccountId,641 to: &T::CrossAccountId,642 amount: u128,643 ) -> DispatchResult {644 if collection.permissions.access() == AccessMode::AllowList {645 collection.check_allowlist(sender)?;646 collection.check_allowlist(from)?;647 collection.check_allowlist(to)?;648 }649650 ensure!(651 sender.conv_eq(from),652 <CommonError<T>>::AddressIsNotEthMirror653 );654655 if <Balance<T>>::get((collection.id, from)) < amount {656 ensure!(657 collection.limits.owner_can_transfer()658 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),659 <CommonError<T>>::CantApproveMoreThanOwned660 );661 }662663 664665 Self::set_allowance_unchecked(collection, from, to, amount);666 Ok(())667 }668669 670 671 672 673 674 675 676 fn check_allowed(677 collection: &FungibleHandle<T>,678 spender: &T::CrossAccountId,679 from: &T::CrossAccountId,680 amount: u128,681 nesting_budget: &dyn Budget,682 ) -> Result<Option<u128>, DispatchError> {683 if spender.conv_eq(from) {684 return Ok(None);685 }686 if collection.permissions.access() == AccessMode::AllowList {687 688 collection.check_allowlist(spender)?;689 }690691 if collection.ignores_token_restrictions(spender) {692 return Ok(Self::compute_allowance_decrease(693 collection, from, spender, amount,694 ));695 }696697 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {698 ensure!(699 <PalletStructure<T>>::check_indirectly_owned(700 spender.clone(),701 source.0,702 source.1,703 None,704 nesting_budget705 )?,706 <CommonError<T>>::ApprovedValueTooLow,707 );708 return Ok(None);709 }710711 let allowance = Self::compute_allowance_decrease(collection, from, spender, amount);712 ensure!(allowance.is_some(), <CommonError<T>>::ApprovedValueTooLow);713714 Ok(allowance)715 }716717 718 719 fn compute_allowance_decrease(720 collection: &FungibleHandle<T>,721 from: &T::CrossAccountId,722 spender: &T::CrossAccountId,723 amount: u128,724 ) -> Option<u128> {725 <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount)726 }727728 729 730 731 732 pub fn transfer_from(733 collection: &FungibleHandle<T>,734 spender: &T::CrossAccountId,735 from: &T::CrossAccountId,736 to: &T::CrossAccountId,737 amount: u128,738 nesting_budget: &dyn Budget,739 ) -> DispatchResultWithPostInfo {740 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;741742 743744 let mut result = Self::transfer(collection, from, to, amount, nesting_budget);745 add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::check_allowed_raw());746 result?;747748 if let Some(allowance) = allowance {749 Self::set_allowance_unchecked(collection, from, spender, allowance);750 add_weight_to_post_info(751 &mut result,752 <SelfWeightOf<T>>::set_allowance_unchecked_raw(),753 )754 }755 result756 }757758 759 760 761 762 763 pub fn burn_from(764 collection: &FungibleHandle<T>,765 spender: &T::CrossAccountId,766 from: &T::CrossAccountId,767 amount: u128,768 nesting_budget: &dyn Budget,769 ) -> DispatchResult {770 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;771772 773774 Self::burn(collection, from, amount)?;775 if let Some(allowance) = allowance {776 Self::set_allowance_unchecked(collection, from, spender, allowance);777 }778 Ok(())779 }780781 782 783 784 785 786 787 788 pub fn create_item(789 collection: &FungibleHandle<T>,790 sender: &T::CrossAccountId,791 data: CreateItemData<T>,792 nesting_budget: &dyn Budget,793 ) -> DispatchResult {794 Self::create_multiple_items(795 collection,796 sender,797 [(data.0, data.1)].into_iter().collect(),798 nesting_budget,799 )800 }801802 803 804 805 806 pub fn create_item_foreign(807 collection: &FungibleHandle<T>,808 sender: &T::CrossAccountId,809 data: CreateItemData<T>,810 nesting_budget: &dyn Budget,811 ) -> DispatchResult {812 Self::create_multiple_items_foreign(813 collection,814 sender,815 [(data.0, data.1)].into_iter().collect(),816 nesting_budget,817 )818 }819820 821 822 823 824 825 826 pub fn token_owners(827 collection: CollectionId,828 _token: TokenId,829 ) -> Option<Vec<T::CrossAccountId>> {830 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))831 .map(|(owner, _amount)| owner)832 .take(10)833 .collect();834835 if res.is_empty() {836 None837 } else {838 Some(res)839 }840 }841}