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,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 }131132 #[pallet::config]133 pub trait Config:134 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config135 {136 type WeightInfo: WeightInfo;137 }138139 #[pallet::pallet]140 #[pallet::generate_store(pub(super) trait Store)]141 pub struct Pallet<T>(_);142143 144 #[pallet::storage]145 pub type TotalSupply<T: Config> =146 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;147148 149 #[pallet::storage]150 pub type Balance<T: Config> = StorageNMap<151 Key = (152 Key<Twox64Concat, CollectionId>,153 Key<Blake2_128Concat, T::CrossAccountId>,154 ),155 Value = u128,156 QueryKind = ValueQuery,157 >;158159 160 #[pallet::storage]161 pub type Allowance<T: Config> = StorageNMap<162 Key = (163 Key<Twox64Concat, CollectionId>,164 Key<Blake2_128, T::CrossAccountId>,165 Key<Blake2_128Concat, T::CrossAccountId>,166 ),167 Value = u128,168 QueryKind = ValueQuery,169 >;170}171172173174pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);175176177impl<T: Config> FungibleHandle<T> {178 179 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {180 Self(inner)181 }182183 184 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {185 self.0186 }187 188 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {189 &mut self.0190 }191}192impl<T: Config> WithRecorder<T> for FungibleHandle<T> {193 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {194 self.0.recorder()195 }196 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {197 self.0.into_recorder()198 }199}200impl<T: Config> Deref for FungibleHandle<T> {201 type Target = pallet_common::CollectionHandle<T>;202203 fn deref(&self) -> &Self::Target {204 &self.0205 }206}207208209impl<T: Config> Pallet<T> {210 211 pub fn init_collection(212 owner: T::CrossAccountId,213 payer: T::CrossAccountId,214 data: CreateCollectionData<T::AccountId>,215 flags: CollectionFlags,216 ) -> Result<CollectionId, DispatchError> {217 <PalletCommon<T>>::init_collection(owner, payer, data, flags)218 }219220 221 pub fn init_foreign_collection(222 owner: T::CrossAccountId,223 payer: T::CrossAccountId,224 data: CreateCollectionData<T::AccountId>,225 ) -> Result<CollectionId, DispatchError> {226 let id = <PalletCommon<T>>::init_collection(227 owner,228 payer,229 data,230 CollectionFlags {231 foreign: true,232 ..Default::default()233 },234 )?;235 Ok(id)236 }237238 239 pub fn destroy_collection(240 collection: FungibleHandle<T>,241 sender: &T::CrossAccountId,242 ) -> DispatchResult {243 let id = collection.id;244245 if Self::collection_has_tokens(id) {246 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());247 }248249 250251 PalletCommon::destroy_collection(collection.0, sender)?;252253 <TotalSupply<T>>::remove(id);254 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);255 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);256 Ok(())257 }258259 260 fn collection_has_tokens(collection_id: CollectionId) -> bool {261 <TotalSupply<T>>::get(collection_id) != 0262 }263264 265 266 267 pub fn burn(268 collection: &FungibleHandle<T>,269 owner: &T::CrossAccountId,270 amount: u128,271 ) -> DispatchResult {272 let total_supply = <TotalSupply<T>>::get(collection.id)273 .checked_sub(amount)274 .ok_or(<CommonError<T>>::TokenValueTooLow)?;275276 let balance = <Balance<T>>::get((collection.id, owner))277 .checked_sub(amount)278 .ok_or(<CommonError<T>>::TokenValueTooLow)?;279280 281 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);282283 if collection.permissions.access() == AccessMode::AllowList {284 collection.check_allowlist(owner)?;285 }286287 288289 if balance == 0 {290 <Balance<T>>::remove((collection.id, owner));291 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());292 } else {293 <Balance<T>>::insert((collection.id, owner), balance);294 }295 <TotalSupply<T>>::insert(collection.id, total_supply);296297 <PalletEvm<T>>::deposit_log(298 ERC20Events::Transfer {299 from: *owner.as_eth(),300 to: H160::default(),301 value: amount.into(),302 }303 .to_log(collection_id_to_address(collection.id)),304 );305 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(306 collection.id,307 TokenId::default(),308 owner.clone(),309 amount,310 ));311 Ok(())312 }313314 315 pub fn burn_foreign(316 collection: &FungibleHandle<T>,317 owner: &T::CrossAccountId,318 amount: u128,319 ) -> DispatchResult {320 let total_supply = <TotalSupply<T>>::get(collection.id)321 .checked_sub(amount)322 .ok_or(<CommonError<T>>::TokenValueTooLow)?;323324 let balance = <Balance<T>>::get((collection.id, owner))325 .checked_sub(amount)326 .ok_or(<CommonError<T>>::TokenValueTooLow)?;327 328329 if balance == 0 {330 <Balance<T>>::remove((collection.id, owner));331 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());332 } else {333 <Balance<T>>::insert((collection.id, owner), balance);334 }335 <TotalSupply<T>>::insert(collection.id, total_supply);336337 <PalletEvm<T>>::deposit_log(338 ERC20Events::Transfer {339 from: *owner.as_eth(),340 to: H160::default(),341 value: amount.into(),342 }343 .to_log(collection_id_to_address(collection.id)),344 );345 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(346 collection.id,347 TokenId::default(),348 owner.clone(),349 amount,350 ));351 Ok(())352 }353354 355 356 357 358 359 360 361 pub fn transfer(362 collection: &FungibleHandle<T>,363 from: &T::CrossAccountId,364 to: &T::CrossAccountId,365 amount: u128,366 nesting_budget: &dyn Budget,367 ) -> DispatchResult {368 ensure!(369 collection.limits.transfers_enabled(),370 <CommonError<T>>::TransferNotAllowed,371 );372373 if collection.permissions.access() == AccessMode::AllowList {374 collection.check_allowlist(from)?;375 collection.check_allowlist(to)?;376 }377 <PalletCommon<T>>::ensure_correct_receiver(to)?;378379 let balance_from = <Balance<T>>::get((collection.id, from))380 .checked_sub(amount)381 .ok_or(<CommonError<T>>::TokenValueTooLow)?;382 let balance_to = if from != to && amount != 0 {383 Some(384 <Balance<T>>::get((collection.id, to))385 .checked_add(amount)386 .ok_or(ArithmeticError::Overflow)?,387 )388 } else {389 None390 };391392 393394 if let Some(balance_to) = balance_to {395 396397 <PalletStructure<T>>::nest_if_sent_to_token(398 from.clone(),399 to,400 collection.id,401 TokenId::default(),402 nesting_budget,403 )?;404405 if balance_from == 0 {406 <Balance<T>>::remove((collection.id, from));407 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());408 } else {409 <Balance<T>>::insert((collection.id, from), balance_from);410 }411 <Balance<T>>::insert((collection.id, to), balance_to);412 }413414 <PalletEvm<T>>::deposit_log(415 ERC20Events::Transfer {416 from: *from.as_eth(),417 to: *to.as_eth(),418 value: amount.into(),419 }420 .to_log(collection_id_to_address(collection.id)),421 );422 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(423 collection.id,424 TokenId::default(),425 from.clone(),426 to.clone(),427 amount,428 ));429 Ok(())430 }431432 433 434 435 pub fn create_multiple_items_common(436 collection: &FungibleHandle<T>,437 sender: &T::CrossAccountId,438 data: BTreeMap<T::CrossAccountId, u128>,439 nesting_budget: &dyn Budget,440 ) -> DispatchResult {441 let total_supply = data442 .iter()443 .map(|(_, v)| *v)444 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {445 acc.checked_add(v)446 })447 .ok_or(ArithmeticError::Overflow)?;448449 for (to, _) in data.iter() {450 <PalletStructure<T>>::check_nesting(451 sender.clone(),452 to,453 collection.id,454 TokenId::default(),455 nesting_budget,456 )?;457 }458459 let updated_balances = data460 .into_iter()461 .map(|(user, amount)| {462 let updated_balance = <Balance<T>>::get((collection.id, &user))463 .checked_add(amount)464 .ok_or(ArithmeticError::Overflow)?;465 Ok((user, amount, updated_balance))466 })467 .collect::<Result<Vec<_>, DispatchError>>()?;468469 470471 <TotalSupply<T>>::insert(collection.id, total_supply);472 for (user, amount, updated_balance) in updated_balances {473 <Balance<T>>::insert((collection.id, &user), updated_balance);474 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(475 &user,476 collection.id,477 TokenId::default(),478 );479 <PalletEvm<T>>::deposit_log(480 ERC20Events::Transfer {481 from: H160::default(),482 to: *user.as_eth(),483 value: amount.into(),484 }485 .to_log(collection_id_to_address(collection.id)),486 );487 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(488 collection.id,489 TokenId::default(),490 user.clone(),491 amount,492 ));493 }494495 Ok(())496 }497498 499 500 pub fn create_multiple_items(501 collection: &FungibleHandle<T>,502 sender: &T::CrossAccountId,503 data: BTreeMap<T::CrossAccountId, u128>,504 nesting_budget: &dyn Budget,505 ) -> DispatchResult {506 507 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);508509 if !collection.is_owner_or_admin(sender) {510 ensure!(511 collection.permissions.mint_mode(),512 <CommonError<T>>::PublicMintingNotAllowed513 );514 collection.check_allowlist(sender)?;515516 for (owner, _) in data.iter() {517 collection.check_allowlist(owner)?;518 }519 }520521 Self::create_multiple_items_common(collection, sender, data, nesting_budget)522 }523524 525 526 pub fn create_multiple_items_foreign(527 collection: &FungibleHandle<T>,528 sender: &T::CrossAccountId,529 data: BTreeMap<T::CrossAccountId, u128>,530 nesting_budget: &dyn Budget,531 ) -> DispatchResult {532 Self::create_multiple_items_common(collection, sender, data, nesting_budget)533 }534535 fn set_allowance_unchecked(536 collection: &FungibleHandle<T>,537 owner: &T::CrossAccountId,538 spender: &T::CrossAccountId,539 amount: u128,540 ) {541 if amount == 0 {542 <Allowance<T>>::remove((collection.id, owner, spender));543 } else {544 <Allowance<T>>::insert((collection.id, owner, spender), amount);545 }546547 <PalletEvm<T>>::deposit_log(548 ERC20Events::Approval {549 owner: *owner.as_eth(),550 spender: *spender.as_eth(),551 value: amount.into(),552 }553 .to_log(collection_id_to_address(collection.id)),554 );555 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(556 collection.id,557 TokenId(0),558 owner.clone(),559 spender.clone(),560 amount,561 ));562 }563564 565 566 567 568 569 570 pub fn set_allowance(571 collection: &FungibleHandle<T>,572 owner: &T::CrossAccountId,573 spender: &T::CrossAccountId,574 amount: u128,575 ) -> DispatchResult {576 if collection.permissions.access() == AccessMode::AllowList {577 collection.check_allowlist(owner)?;578 collection.check_allowlist(spender)?;579 }580581 if <Balance<T>>::get((collection.id, owner)) < amount {582 ensure!(583 collection.ignores_owned_amount(owner),584 <CommonError<T>>::CantApproveMoreThanOwned585 );586 }587588 589590 Self::set_allowance_unchecked(collection, owner, spender, amount);591 Ok(())592 }593594 595 596 597 598 599 600 601 fn check_allowed(602 collection: &FungibleHandle<T>,603 spender: &T::CrossAccountId,604 from: &T::CrossAccountId,605 amount: u128,606 nesting_budget: &dyn Budget,607 ) -> Result<Option<u128>, DispatchError> {608 if spender.conv_eq(from) {609 return Ok(None);610 }611 if collection.permissions.access() == AccessMode::AllowList {612 613 collection.check_allowlist(spender)?;614 }615 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {616 617 ensure!(618 <PalletStructure<T>>::check_indirectly_owned(619 spender.clone(),620 source.0,621 source.1,622 None,623 nesting_budget624 )?,625 <CommonError<T>>::ApprovedValueTooLow,626 );627 return Ok(None);628 }629 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);630 if allowance.is_none() {631 ensure!(632 collection.ignores_allowance(spender),633 <CommonError<T>>::ApprovedValueTooLow634 );635 }636637 Ok(allowance)638 }639640 641 642 643 644645 pub fn transfer_from(646 collection: &FungibleHandle<T>,647 spender: &T::CrossAccountId,648 from: &T::CrossAccountId,649 to: &T::CrossAccountId,650 amount: u128,651 nesting_budget: &dyn Budget,652 ) -> DispatchResult {653 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;654655 656657 Self::transfer(collection, from, to, amount, nesting_budget)?;658 if let Some(allowance) = allowance {659 Self::set_allowance_unchecked(collection, from, spender, allowance);660 }661 Ok(())662 }663664 665 666 667 668 669 pub fn burn_from(670 collection: &FungibleHandle<T>,671 spender: &T::CrossAccountId,672 from: &T::CrossAccountId,673 amount: u128,674 nesting_budget: &dyn Budget,675 ) -> DispatchResult {676 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;677678 679680 Self::burn(collection, from, amount)?;681 if let Some(allowance) = allowance {682 Self::set_allowance_unchecked(collection, from, spender, allowance);683 }684 Ok(())685 }686687 688 689 690 691 692 693 694 pub fn create_item(695 collection: &FungibleHandle<T>,696 sender: &T::CrossAccountId,697 data: CreateItemData<T>,698 nesting_budget: &dyn Budget,699 ) -> DispatchResult {700 Self::create_multiple_items(701 collection,702 sender,703 [(data.0, data.1)].into_iter().collect(),704 nesting_budget,705 )706 }707708 709 710 711 712 pub fn create_item_foreign(713 collection: &FungibleHandle<T>,714 sender: &T::CrossAccountId,715 data: CreateItemData<T>,716 nesting_budget: &dyn Budget,717 ) -> DispatchResult {718 Self::create_multiple_items_foreign(719 collection,720 sender,721 [(data.0, data.1)].into_iter().collect(),722 nesting_budget,723 )724 }725726 727 728 729 730 731 732 pub fn token_owners(733 collection: CollectionId,734 _token: TokenId,735 ) -> Option<Vec<T::CrossAccountId>> {736 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))737 .map(|(owner, _amount)| owner)738 .take(10)739 .collect();740741 if res.is_empty() {742 None743 } else {744 Some(res)745 }746 }747}