12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879#![cfg_attr(not(feature = "std"), no_std)]8081use core::ops::Deref;82use evm_coder::ToLog;83use frame_support::ensure;84use pallet_evm::account::CrossAccountId;85use up_data_structs::{86 AccessMode, CollectionId, CollectionFlags, TokenId, CreateCollectionData,87 mapping::TokenAddressMapping, budget::Budget, PropertyKey, Property,88};89use pallet_common::{90 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,91 eth::collection_id_to_address,92};93use pallet_evm::Pallet as PalletEvm;94use pallet_structure::Pallet as PalletStructure;95use pallet_evm_coder_substrate::WithRecorder;96use sp_core::H160;97use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};98use sp_std::{collections::btree_map::BTreeMap, vec::Vec};99100pub use pallet::*;101102use crate::erc::ERC20Events;103#[cfg(feature = "runtime-benchmarks")]104pub mod benchmarking;105pub mod common;106pub mod erc;107pub mod weights;108109pub type CreateItemData<T> = (<T as pallet_evm::Config>::CrossAccountId, u128);110pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;111112#[frame_support::pallet]113pub mod pallet {114 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};115 use up_data_structs::CollectionId;116 use super::weights::WeightInfo;117118 #[pallet::error]119 pub enum Error<T> {120 121 NotFungibleDataUsedToMintFungibleCollectionToken,122 123 FungibleItemsHaveNoId,124 125 FungibleItemsDontHaveData,126 127 FungibleDisallowsNesting,128 129 SettingPropertiesNotAllowed,130 131 SettingAllowanceForAllNotAllowed,132 133 FungibleTokensAreAlwaysValid,134 }135136 #[pallet::config]137 pub trait Config:138 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config139 {140 type WeightInfo: WeightInfo;141 }142143 #[pallet::pallet]144 #[pallet::generate_store(pub(super) trait Store)]145 pub struct Pallet<T>(_);146147 148 #[pallet::storage]149 pub type TotalSupply<T: Config> =150 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;151152 153 #[pallet::storage]154 pub type Balance<T: Config> = StorageNMap<155 Key = (156 Key<Twox64Concat, CollectionId>,157 Key<Blake2_128Concat, T::CrossAccountId>,158 ),159 Value = u128,160 QueryKind = ValueQuery,161 >;162163 164 #[pallet::storage]165 pub type Allowance<T: Config> = StorageNMap<166 Key = (167 Key<Twox64Concat, CollectionId>,168 Key<Blake2_128, T::CrossAccountId>,169 Key<Blake2_128Concat, T::CrossAccountId>,170 ),171 Value = u128,172 QueryKind = ValueQuery,173 >;174}175176177178pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);179180181impl<T: Config> FungibleHandle<T> {182 183 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {184 Self(inner)185 }186187 188 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {189 self.0190 }191 192 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {193 &mut self.0194 }195}196impl<T: Config> WithRecorder<T> for FungibleHandle<T> {197 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {198 self.0.recorder()199 }200 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {201 self.0.into_recorder()202 }203}204impl<T: Config> Deref for FungibleHandle<T> {205 type Target = pallet_common::CollectionHandle<T>;206207 fn deref(&self) -> &Self::Target {208 &self.0209 }210}211212213impl<T: Config> Pallet<T> {214 215 pub fn init_collection(216 owner: T::CrossAccountId,217 payer: T::CrossAccountId,218 data: CreateCollectionData<T::AccountId>,219 flags: CollectionFlags,220 ) -> Result<CollectionId, DispatchError> {221 <PalletCommon<T>>::init_collection(owner, payer, data, flags)222 }223224 225 pub fn init_foreign_collection(226 owner: T::CrossAccountId,227 payer: T::CrossAccountId,228 data: CreateCollectionData<T::AccountId>,229 ) -> Result<CollectionId, DispatchError> {230 let id = <PalletCommon<T>>::init_collection(231 owner,232 payer,233 data,234 CollectionFlags {235 foreign: true,236 ..Default::default()237 },238 )?;239 Ok(id)240 }241242 243 pub fn destroy_collection(244 collection: FungibleHandle<T>,245 sender: &T::CrossAccountId,246 ) -> DispatchResult {247 let id = collection.id;248249 if Self::collection_has_tokens(id) {250 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());251 }252253 254255 PalletCommon::destroy_collection(collection.0, sender)?;256257 <TotalSupply<T>>::remove(id);258 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);259 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);260 Ok(())261 }262263 264 pub fn set_collection_properties(265 collection: &FungibleHandle<T>,266 sender: &T::CrossAccountId,267 properties: Vec<Property>,268 ) -> DispatchResult {269 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())270 }271272 273 pub fn delete_collection_properties(274 collection: &FungibleHandle<T>,275 sender: &T::CrossAccountId,276 property_keys: Vec<PropertyKey>,277 ) -> DispatchResult {278 <PalletCommon<T>>::delete_collection_properties(279 collection,280 sender,281 property_keys.into_iter(),282 )283 }284285 286 fn collection_has_tokens(collection_id: CollectionId) -> bool {287 <TotalSupply<T>>::get(collection_id) != 0288 }289290 291 292 293 pub fn burn(294 collection: &FungibleHandle<T>,295 owner: &T::CrossAccountId,296 amount: u128,297 ) -> DispatchResult {298 let total_supply = <TotalSupply<T>>::get(collection.id)299 .checked_sub(amount)300 .ok_or(<CommonError<T>>::TokenValueTooLow)?;301302 let balance = <Balance<T>>::get((collection.id, owner))303 .checked_sub(amount)304 .ok_or(<CommonError<T>>::TokenValueTooLow)?;305306 307 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);308309 if collection.permissions.access() == AccessMode::AllowList {310 collection.check_allowlist(owner)?;311 }312313 314315 if balance == 0 {316 <Balance<T>>::remove((collection.id, owner));317 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());318 } else {319 <Balance<T>>::insert((collection.id, owner), balance);320 }321 <TotalSupply<T>>::insert(collection.id, total_supply);322323 <PalletEvm<T>>::deposit_log(324 ERC20Events::Transfer {325 from: *owner.as_eth(),326 to: H160::default(),327 value: amount.into(),328 }329 .to_log(collection_id_to_address(collection.id)),330 );331 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(332 collection.id,333 TokenId::default(),334 owner.clone(),335 amount,336 ));337 Ok(())338 }339340 341 pub fn burn_foreign(342 collection: &FungibleHandle<T>,343 owner: &T::CrossAccountId,344 amount: u128,345 ) -> DispatchResult {346 let total_supply = <TotalSupply<T>>::get(collection.id)347 .checked_sub(amount)348 .ok_or(<CommonError<T>>::TokenValueTooLow)?;349350 let balance = <Balance<T>>::get((collection.id, owner))351 .checked_sub(amount)352 .ok_or(<CommonError<T>>::TokenValueTooLow)?;353 354355 if balance == 0 {356 <Balance<T>>::remove((collection.id, owner));357 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());358 } else {359 <Balance<T>>::insert((collection.id, owner), balance);360 }361 <TotalSupply<T>>::insert(collection.id, total_supply);362363 <PalletEvm<T>>::deposit_log(364 ERC20Events::Transfer {365 from: *owner.as_eth(),366 to: H160::default(),367 value: amount.into(),368 }369 .to_log(collection_id_to_address(collection.id)),370 );371 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(372 collection.id,373 TokenId::default(),374 owner.clone(),375 amount,376 ));377 Ok(())378 }379380 381 382 383 384 385 386 387 pub fn transfer(388 collection: &FungibleHandle<T>,389 from: &T::CrossAccountId,390 to: &T::CrossAccountId,391 amount: u128,392 nesting_budget: &dyn Budget,393 ) -> DispatchResult {394 ensure!(395 collection.limits.transfers_enabled(),396 <CommonError<T>>::TransferNotAllowed,397 );398399 if collection.permissions.access() == AccessMode::AllowList {400 collection.check_allowlist(from)?;401 collection.check_allowlist(to)?;402 }403 <PalletCommon<T>>::ensure_correct_receiver(to)?;404405 let balance_from = <Balance<T>>::get((collection.id, from))406 .checked_sub(amount)407 .ok_or(<CommonError<T>>::TokenValueTooLow)?;408 let balance_to = if from != to && amount != 0 {409 Some(410 <Balance<T>>::get((collection.id, to))411 .checked_add(amount)412 .ok_or(ArithmeticError::Overflow)?,413 )414 } else {415 None416 };417418 419420 if let Some(balance_to) = balance_to {421 422423 <PalletStructure<T>>::nest_if_sent_to_token(424 from.clone(),425 to,426 collection.id,427 TokenId::default(),428 nesting_budget,429 )?;430431 if balance_from == 0 {432 <Balance<T>>::remove((collection.id, from));433 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());434 } else {435 <Balance<T>>::insert((collection.id, from), balance_from);436 }437 <Balance<T>>::insert((collection.id, to), balance_to);438 }439440 <PalletEvm<T>>::deposit_log(441 ERC20Events::Transfer {442 from: *from.as_eth(),443 to: *to.as_eth(),444 value: amount.into(),445 }446 .to_log(collection_id_to_address(collection.id)),447 );448 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(449 collection.id,450 TokenId::default(),451 from.clone(),452 to.clone(),453 amount,454 ));455 Ok(())456 }457458 459 460 461 pub fn create_multiple_items_common(462 collection: &FungibleHandle<T>,463 sender: &T::CrossAccountId,464 data: BTreeMap<T::CrossAccountId, u128>,465 nesting_budget: &dyn Budget,466 ) -> DispatchResult {467 let total_supply = data468 .iter()469 .map(|(_, v)| *v)470 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {471 acc.checked_add(v)472 })473 .ok_or(ArithmeticError::Overflow)?;474475 for (to, _) in data.iter() {476 <PalletStructure<T>>::check_nesting(477 sender.clone(),478 to,479 collection.id,480 TokenId::default(),481 nesting_budget,482 )?;483 }484485 let updated_balances = data486 .into_iter()487 .map(|(user, amount)| {488 let updated_balance = <Balance<T>>::get((collection.id, &user))489 .checked_add(amount)490 .ok_or(ArithmeticError::Overflow)?;491 Ok((user, amount, updated_balance))492 })493 .collect::<Result<Vec<_>, DispatchError>>()?;494495 496497 <TotalSupply<T>>::insert(collection.id, total_supply);498 for (user, amount, updated_balance) in updated_balances {499 <Balance<T>>::insert((collection.id, &user), updated_balance);500 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(501 &user,502 collection.id,503 TokenId::default(),504 );505 <PalletEvm<T>>::deposit_log(506 ERC20Events::Transfer {507 from: H160::default(),508 to: *user.as_eth(),509 value: amount.into(),510 }511 .to_log(collection_id_to_address(collection.id)),512 );513 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(514 collection.id,515 TokenId::default(),516 user.clone(),517 amount,518 ));519 }520521 Ok(())522 }523524 525 526 pub fn create_multiple_items(527 collection: &FungibleHandle<T>,528 sender: &T::CrossAccountId,529 data: BTreeMap<T::CrossAccountId, u128>,530 nesting_budget: &dyn Budget,531 ) -> DispatchResult {532 533 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);534535 if !collection.is_owner_or_admin(sender) {536 ensure!(537 collection.permissions.mint_mode(),538 <CommonError<T>>::PublicMintingNotAllowed539 );540 collection.check_allowlist(sender)?;541542 for (owner, _) in data.iter() {543 collection.check_allowlist(owner)?;544 }545 }546547 Self::create_multiple_items_common(collection, sender, data, nesting_budget)548 }549550 551 552 pub fn create_multiple_items_foreign(553 collection: &FungibleHandle<T>,554 sender: &T::CrossAccountId,555 data: BTreeMap<T::CrossAccountId, u128>,556 nesting_budget: &dyn Budget,557 ) -> DispatchResult {558 Self::create_multiple_items_common(collection, sender, data, nesting_budget)559 }560561 fn set_allowance_unchecked(562 collection: &FungibleHandle<T>,563 owner: &T::CrossAccountId,564 spender: &T::CrossAccountId,565 amount: u128,566 ) {567 if amount == 0 {568 <Allowance<T>>::remove((collection.id, owner, spender));569 } else {570 <Allowance<T>>::insert((collection.id, owner, spender), amount);571 }572573 <PalletEvm<T>>::deposit_log(574 ERC20Events::Approval {575 owner: *owner.as_eth(),576 spender: *spender.as_eth(),577 value: amount.into(),578 }579 .to_log(collection_id_to_address(collection.id)),580 );581 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(582 collection.id,583 TokenId(0),584 owner.clone(),585 spender.clone(),586 amount,587 ));588 }589590 591 592 593 594 595 596 pub fn set_allowance(597 collection: &FungibleHandle<T>,598 owner: &T::CrossAccountId,599 spender: &T::CrossAccountId,600 amount: u128,601 ) -> DispatchResult {602 if collection.permissions.access() == AccessMode::AllowList {603 collection.check_allowlist(owner)?;604 collection.check_allowlist(spender)?;605 }606607 if <Balance<T>>::get((collection.id, owner)) < amount {608 ensure!(609 collection.ignores_owned_amount(owner),610 <CommonError<T>>::CantApproveMoreThanOwned611 );612 }613614 615616 Self::set_allowance_unchecked(collection, owner, spender, amount);617 Ok(())618 }619620 621 622 623 624 625 626 627 pub fn set_allowance_from(628 collection: &FungibleHandle<T>,629 sender: &T::CrossAccountId,630 from: &T::CrossAccountId,631 to: &T::CrossAccountId,632 amount: u128,633 ) -> DispatchResult {634 if collection.permissions.access() == AccessMode::AllowList {635 collection.check_allowlist(sender)?;636 collection.check_allowlist(from)?;637 collection.check_allowlist(to)?;638 }639640 ensure!(641 sender.conv_eq(from),642 <CommonError<T>>::AddressIsNotEthMirror643 );644645 if <Balance<T>>::get((collection.id, from)) < amount {646 ensure!(647 collection.limits.owner_can_transfer()648 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),649 <CommonError<T>>::CantApproveMoreThanOwned650 );651 }652653 654655 Self::set_allowance_unchecked(collection, from, to, amount);656 Ok(())657 }658659 660 661 662 663 664 665 666 fn check_allowed(667 collection: &FungibleHandle<T>,668 spender: &T::CrossAccountId,669 from: &T::CrossAccountId,670 amount: u128,671 nesting_budget: &dyn Budget,672 ) -> Result<Option<u128>, DispatchError> {673 if spender.conv_eq(from) {674 return Ok(None);675 }676 if collection.permissions.access() == AccessMode::AllowList {677 678 collection.check_allowlist(spender)?;679 }680681 if collection.ignores_token_restrictions(spender) {682 return Ok(Self::compute_allowance_decrease(683 collection, from, spender, amount,684 ));685 }686687 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {688 ensure!(689 <PalletStructure<T>>::check_indirectly_owned(690 spender.clone(),691 source.0,692 source.1,693 None,694 nesting_budget695 )?,696 <CommonError<T>>::ApprovedValueTooLow,697 );698 return Ok(None);699 }700701 let allowance = Self::compute_allowance_decrease(collection, from, spender, amount);702 ensure!(allowance.is_some(), <CommonError<T>>::ApprovedValueTooLow);703704 Ok(allowance)705 }706707 708 709 fn compute_allowance_decrease(710 collection: &FungibleHandle<T>,711 from: &T::CrossAccountId,712 spender: &T::CrossAccountId,713 amount: u128,714 ) -> Option<u128> {715 <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount)716 }717718 719 720 721 722723 pub fn transfer_from(724 collection: &FungibleHandle<T>,725 spender: &T::CrossAccountId,726 from: &T::CrossAccountId,727 to: &T::CrossAccountId,728 amount: u128,729 nesting_budget: &dyn Budget,730 ) -> DispatchResult {731 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;732733 734735 Self::transfer(collection, from, to, amount, nesting_budget)?;736 if let Some(allowance) = allowance {737 Self::set_allowance_unchecked(collection, from, spender, allowance);738 }739 Ok(())740 }741742 743 744 745 746 747 pub fn burn_from(748 collection: &FungibleHandle<T>,749 spender: &T::CrossAccountId,750 from: &T::CrossAccountId,751 amount: u128,752 nesting_budget: &dyn Budget,753 ) -> DispatchResult {754 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;755756 757758 Self::burn(collection, from, amount)?;759 if let Some(allowance) = allowance {760 Self::set_allowance_unchecked(collection, from, spender, allowance);761 }762 Ok(())763 }764765 766 767 768 769 770 771 772 pub fn create_item(773 collection: &FungibleHandle<T>,774 sender: &T::CrossAccountId,775 data: CreateItemData<T>,776 nesting_budget: &dyn Budget,777 ) -> DispatchResult {778 Self::create_multiple_items(779 collection,780 sender,781 [(data.0, data.1)].into_iter().collect(),782 nesting_budget,783 )784 }785786 787 788 789 790 pub fn create_item_foreign(791 collection: &FungibleHandle<T>,792 sender: &T::CrossAccountId,793 data: CreateItemData<T>,794 nesting_budget: &dyn Budget,795 ) -> DispatchResult {796 Self::create_multiple_items_foreign(797 collection,798 sender,799 [(data.0, data.1)].into_iter().collect(),800 nesting_budget,801 )802 }803804 805 806 807 808 809 810 pub fn token_owners(811 collection: CollectionId,812 _token: TokenId,813 ) -> Option<Vec<T::CrossAccountId>> {814 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))815 .map(|(owner, _amount)| owner)816 .take(10)817 .collect();818819 if res.is_empty() {820 None821 } else {822 Some(res)823 }824 }825}