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)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(collection, sender, property_keys)279 }280281 282 fn collection_has_tokens(collection_id: CollectionId) -> bool {283 <TotalSupply<T>>::get(collection_id) != 0284 }285286 287 288 289 pub fn burn(290 collection: &FungibleHandle<T>,291 owner: &T::CrossAccountId,292 amount: u128,293 ) -> DispatchResult {294 let total_supply = <TotalSupply<T>>::get(collection.id)295 .checked_sub(amount)296 .ok_or(<CommonError<T>>::TokenValueTooLow)?;297298 let balance = <Balance<T>>::get((collection.id, owner))299 .checked_sub(amount)300 .ok_or(<CommonError<T>>::TokenValueTooLow)?;301302 303 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);304305 if collection.permissions.access() == AccessMode::AllowList {306 collection.check_allowlist(owner)?;307 }308309 310311 if balance == 0 {312 <Balance<T>>::remove((collection.id, owner));313 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());314 } else {315 <Balance<T>>::insert((collection.id, owner), balance);316 }317 <TotalSupply<T>>::insert(collection.id, total_supply);318319 <PalletEvm<T>>::deposit_log(320 ERC20Events::Transfer {321 from: *owner.as_eth(),322 to: H160::default(),323 value: amount.into(),324 }325 .to_log(collection_id_to_address(collection.id)),326 );327 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(328 collection.id,329 TokenId::default(),330 owner.clone(),331 amount,332 ));333 Ok(())334 }335336 337 pub fn burn_foreign(338 collection: &FungibleHandle<T>,339 owner: &T::CrossAccountId,340 amount: u128,341 ) -> DispatchResult {342 let total_supply = <TotalSupply<T>>::get(collection.id)343 .checked_sub(amount)344 .ok_or(<CommonError<T>>::TokenValueTooLow)?;345346 let balance = <Balance<T>>::get((collection.id, owner))347 .checked_sub(amount)348 .ok_or(<CommonError<T>>::TokenValueTooLow)?;349 350351 if balance == 0 {352 <Balance<T>>::remove((collection.id, owner));353 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());354 } else {355 <Balance<T>>::insert((collection.id, owner), balance);356 }357 <TotalSupply<T>>::insert(collection.id, total_supply);358359 <PalletEvm<T>>::deposit_log(360 ERC20Events::Transfer {361 from: *owner.as_eth(),362 to: H160::default(),363 value: amount.into(),364 }365 .to_log(collection_id_to_address(collection.id)),366 );367 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(368 collection.id,369 TokenId::default(),370 owner.clone(),371 amount,372 ));373 Ok(())374 }375376 377 378 379 380 381 382 383 pub fn transfer(384 collection: &FungibleHandle<T>,385 from: &T::CrossAccountId,386 to: &T::CrossAccountId,387 amount: u128,388 nesting_budget: &dyn Budget,389 ) -> DispatchResult {390 ensure!(391 collection.limits.transfers_enabled(),392 <CommonError<T>>::TransferNotAllowed,393 );394395 if collection.permissions.access() == AccessMode::AllowList {396 collection.check_allowlist(from)?;397 collection.check_allowlist(to)?;398 }399 <PalletCommon<T>>::ensure_correct_receiver(to)?;400401 let balance_from = <Balance<T>>::get((collection.id, from))402 .checked_sub(amount)403 .ok_or(<CommonError<T>>::TokenValueTooLow)?;404 let balance_to = if from != to && amount != 0 {405 Some(406 <Balance<T>>::get((collection.id, to))407 .checked_add(amount)408 .ok_or(ArithmeticError::Overflow)?,409 )410 } else {411 None412 };413414 415416 if let Some(balance_to) = balance_to {417 418419 <PalletStructure<T>>::nest_if_sent_to_token(420 from.clone(),421 to,422 collection.id,423 TokenId::default(),424 nesting_budget,425 )?;426427 if balance_from == 0 {428 <Balance<T>>::remove((collection.id, from));429 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());430 } else {431 <Balance<T>>::insert((collection.id, from), balance_from);432 }433 <Balance<T>>::insert((collection.id, to), balance_to);434 }435436 <PalletEvm<T>>::deposit_log(437 ERC20Events::Transfer {438 from: *from.as_eth(),439 to: *to.as_eth(),440 value: amount.into(),441 }442 .to_log(collection_id_to_address(collection.id)),443 );444 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(445 collection.id,446 TokenId::default(),447 from.clone(),448 to.clone(),449 amount,450 ));451 Ok(())452 }453454 455 456 457 pub fn create_multiple_items_common(458 collection: &FungibleHandle<T>,459 sender: &T::CrossAccountId,460 data: BTreeMap<T::CrossAccountId, u128>,461 nesting_budget: &dyn Budget,462 ) -> DispatchResult {463 let total_supply = data464 .iter()465 .map(|(_, v)| *v)466 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {467 acc.checked_add(v)468 })469 .ok_or(ArithmeticError::Overflow)?;470471 for (to, _) in data.iter() {472 <PalletStructure<T>>::check_nesting(473 sender.clone(),474 to,475 collection.id,476 TokenId::default(),477 nesting_budget,478 )?;479 }480481 let updated_balances = data482 .into_iter()483 .map(|(user, amount)| {484 let updated_balance = <Balance<T>>::get((collection.id, &user))485 .checked_add(amount)486 .ok_or(ArithmeticError::Overflow)?;487 Ok((user, amount, updated_balance))488 })489 .collect::<Result<Vec<_>, DispatchError>>()?;490491 492493 <TotalSupply<T>>::insert(collection.id, total_supply);494 for (user, amount, updated_balance) in updated_balances {495 <Balance<T>>::insert((collection.id, &user), updated_balance);496 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(497 &user,498 collection.id,499 TokenId::default(),500 );501 <PalletEvm<T>>::deposit_log(502 ERC20Events::Transfer {503 from: H160::default(),504 to: *user.as_eth(),505 value: amount.into(),506 }507 .to_log(collection_id_to_address(collection.id)),508 );509 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(510 collection.id,511 TokenId::default(),512 user.clone(),513 amount,514 ));515 }516517 Ok(())518 }519520 521 522 pub fn create_multiple_items(523 collection: &FungibleHandle<T>,524 sender: &T::CrossAccountId,525 data: BTreeMap<T::CrossAccountId, u128>,526 nesting_budget: &dyn Budget,527 ) -> DispatchResult {528 529 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);530531 if !collection.is_owner_or_admin(sender) {532 ensure!(533 collection.permissions.mint_mode(),534 <CommonError<T>>::PublicMintingNotAllowed535 );536 collection.check_allowlist(sender)?;537538 for (owner, _) in data.iter() {539 collection.check_allowlist(owner)?;540 }541 }542543 Self::create_multiple_items_common(collection, sender, data, nesting_budget)544 }545546 547 548 pub fn create_multiple_items_foreign(549 collection: &FungibleHandle<T>,550 sender: &T::CrossAccountId,551 data: BTreeMap<T::CrossAccountId, u128>,552 nesting_budget: &dyn Budget,553 ) -> DispatchResult {554 Self::create_multiple_items_common(collection, sender, data, nesting_budget)555 }556557 fn set_allowance_unchecked(558 collection: &FungibleHandle<T>,559 owner: &T::CrossAccountId,560 spender: &T::CrossAccountId,561 amount: u128,562 ) {563 if amount == 0 {564 <Allowance<T>>::remove((collection.id, owner, spender));565 } else {566 <Allowance<T>>::insert((collection.id, owner, spender), amount);567 }568569 <PalletEvm<T>>::deposit_log(570 ERC20Events::Approval {571 owner: *owner.as_eth(),572 spender: *spender.as_eth(),573 value: amount.into(),574 }575 .to_log(collection_id_to_address(collection.id)),576 );577 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(578 collection.id,579 TokenId(0),580 owner.clone(),581 spender.clone(),582 amount,583 ));584 }585586 587 588 589 590 591 592 pub fn set_allowance(593 collection: &FungibleHandle<T>,594 owner: &T::CrossAccountId,595 spender: &T::CrossAccountId,596 amount: u128,597 ) -> DispatchResult {598 if collection.permissions.access() == AccessMode::AllowList {599 collection.check_allowlist(owner)?;600 collection.check_allowlist(spender)?;601 }602603 if <Balance<T>>::get((collection.id, owner)) < amount {604 ensure!(605 collection.ignores_owned_amount(owner),606 <CommonError<T>>::CantApproveMoreThanOwned607 );608 }609610 611612 Self::set_allowance_unchecked(collection, owner, spender, amount);613 Ok(())614 }615616 617 618 619 620 621 622 623 fn check_allowed(624 collection: &FungibleHandle<T>,625 spender: &T::CrossAccountId,626 from: &T::CrossAccountId,627 amount: u128,628 nesting_budget: &dyn Budget,629 ) -> Result<Option<u128>, DispatchError> {630 if spender.conv_eq(from) {631 return Ok(None);632 }633 if collection.permissions.access() == AccessMode::AllowList {634 635 collection.check_allowlist(spender)?;636 }637 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {638 639 ensure!(640 <PalletStructure<T>>::check_indirectly_owned(641 spender.clone(),642 source.0,643 source.1,644 None,645 nesting_budget646 )?,647 <CommonError<T>>::ApprovedValueTooLow,648 );649 return Ok(None);650 }651 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);652 if allowance.is_none() {653 ensure!(654 collection.ignores_allowance(spender),655 <CommonError<T>>::ApprovedValueTooLow656 );657 }658659 Ok(allowance)660 }661662 663 664 665 666667 pub fn transfer_from(668 collection: &FungibleHandle<T>,669 spender: &T::CrossAccountId,670 from: &T::CrossAccountId,671 to: &T::CrossAccountId,672 amount: u128,673 nesting_budget: &dyn Budget,674 ) -> DispatchResult {675 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;676677 678679 Self::transfer(collection, from, to, amount, nesting_budget)?;680 if let Some(allowance) = allowance {681 Self::set_allowance_unchecked(collection, from, spender, allowance);682 }683 Ok(())684 }685686 687 688 689 690 691 pub fn burn_from(692 collection: &FungibleHandle<T>,693 spender: &T::CrossAccountId,694 from: &T::CrossAccountId,695 amount: u128,696 nesting_budget: &dyn Budget,697 ) -> DispatchResult {698 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;699700 701702 Self::burn(collection, from, amount)?;703 if let Some(allowance) = allowance {704 Self::set_allowance_unchecked(collection, from, spender, allowance);705 }706 Ok(())707 }708709 710 711 712 713 714 715 716 pub fn create_item(717 collection: &FungibleHandle<T>,718 sender: &T::CrossAccountId,719 data: CreateItemData<T>,720 nesting_budget: &dyn Budget,721 ) -> DispatchResult {722 Self::create_multiple_items(723 collection,724 sender,725 [(data.0, data.1)].into_iter().collect(),726 nesting_budget,727 )728 }729730 731 732 733 734 pub fn create_item_foreign(735 collection: &FungibleHandle<T>,736 sender: &T::CrossAccountId,737 data: CreateItemData<T>,738 nesting_budget: &dyn Budget,739 ) -> DispatchResult {740 Self::create_multiple_items_foreign(741 collection,742 sender,743 [(data.0, data.1)].into_iter().collect(),744 nesting_budget,745 )746 }747748 749 750 751 752 753 754 pub fn token_owners(755 collection: CollectionId,756 _token: TokenId,757 ) -> Option<Vec<T::CrossAccountId>> {758 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))759 .map(|(owner, _amount)| owner)760 .take(10)761 .collect();762763 if res.is_empty() {764 None765 } else {766 Some(res)767 }768 }769}