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 131 SettingApprovalForAllNotAllowed,132 }133134 #[pallet::config]135 pub trait Config:136 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config137 {138 type WeightInfo: WeightInfo;139 }140141 #[pallet::pallet]142 #[pallet::generate_store(pub(super) trait Store)]143 pub struct Pallet<T>(_);144145 146 #[pallet::storage]147 pub type TotalSupply<T: Config> =148 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;149150 151 #[pallet::storage]152 pub type Balance<T: Config> = StorageNMap<153 Key = (154 Key<Twox64Concat, CollectionId>,155 Key<Blake2_128Concat, T::CrossAccountId>,156 ),157 Value = u128,158 QueryKind = ValueQuery,159 >;160161 162 #[pallet::storage]163 pub type Allowance<T: Config> = StorageNMap<164 Key = (165 Key<Twox64Concat, CollectionId>,166 Key<Blake2_128, T::CrossAccountId>,167 Key<Blake2_128Concat, T::CrossAccountId>,168 ),169 Value = u128,170 QueryKind = ValueQuery,171 >;172}173174175176pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);177178179impl<T: Config> FungibleHandle<T> {180 181 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {182 Self(inner)183 }184185 186 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {187 self.0188 }189 190 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {191 &mut self.0192 }193}194impl<T: Config> WithRecorder<T> for FungibleHandle<T> {195 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {196 self.0.recorder()197 }198 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {199 self.0.into_recorder()200 }201}202impl<T: Config> Deref for FungibleHandle<T> {203 type Target = pallet_common::CollectionHandle<T>;204205 fn deref(&self) -> &Self::Target {206 &self.0207 }208}209210211impl<T: Config> Pallet<T> {212 213 pub fn init_collection(214 owner: T::CrossAccountId,215 payer: T::CrossAccountId,216 data: CreateCollectionData<T::AccountId>,217 flags: CollectionFlags,218 ) -> Result<CollectionId, DispatchError> {219 <PalletCommon<T>>::init_collection(owner, payer, data, flags)220 }221222 223 pub fn init_foreign_collection(224 owner: T::CrossAccountId,225 payer: T::CrossAccountId,226 data: CreateCollectionData<T::AccountId>,227 ) -> Result<CollectionId, DispatchError> {228 let id = <PalletCommon<T>>::init_collection(229 owner,230 payer,231 data,232 CollectionFlags {233 foreign: true,234 ..Default::default()235 },236 )?;237 Ok(id)238 }239240 241 pub fn destroy_collection(242 collection: FungibleHandle<T>,243 sender: &T::CrossAccountId,244 ) -> DispatchResult {245 let id = collection.id;246247 if Self::collection_has_tokens(id) {248 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());249 }250251 252253 PalletCommon::destroy_collection(collection.0, sender)?;254255 <TotalSupply<T>>::remove(id);256 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);257 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);258 Ok(())259 }260261 262 fn collection_has_tokens(collection_id: CollectionId) -> bool {263 <TotalSupply<T>>::get(collection_id) != 0264 }265266 267 268 269 pub fn burn(270 collection: &FungibleHandle<T>,271 owner: &T::CrossAccountId,272 amount: u128,273 ) -> DispatchResult {274 let total_supply = <TotalSupply<T>>::get(collection.id)275 .checked_sub(amount)276 .ok_or(<CommonError<T>>::TokenValueTooLow)?;277278 let balance = <Balance<T>>::get((collection.id, owner))279 .checked_sub(amount)280 .ok_or(<CommonError<T>>::TokenValueTooLow)?;281282 283 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);284285 if collection.permissions.access() == AccessMode::AllowList {286 collection.check_allowlist(owner)?;287 }288289 290291 if balance == 0 {292 <Balance<T>>::remove((collection.id, owner));293 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());294 } else {295 <Balance<T>>::insert((collection.id, owner), balance);296 }297 <TotalSupply<T>>::insert(collection.id, total_supply);298299 <PalletEvm<T>>::deposit_log(300 ERC20Events::Transfer {301 from: *owner.as_eth(),302 to: H160::default(),303 value: amount.into(),304 }305 .to_log(collection_id_to_address(collection.id)),306 );307 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(308 collection.id,309 TokenId::default(),310 owner.clone(),311 amount,312 ));313 Ok(())314 }315316 317 pub fn burn_foreign(318 collection: &FungibleHandle<T>,319 owner: &T::CrossAccountId,320 amount: u128,321 ) -> DispatchResult {322 let total_supply = <TotalSupply<T>>::get(collection.id)323 .checked_sub(amount)324 .ok_or(<CommonError<T>>::TokenValueTooLow)?;325326 let balance = <Balance<T>>::get((collection.id, owner))327 .checked_sub(amount)328 .ok_or(<CommonError<T>>::TokenValueTooLow)?;329 330331 if balance == 0 {332 <Balance<T>>::remove((collection.id, owner));333 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());334 } else {335 <Balance<T>>::insert((collection.id, owner), balance);336 }337 <TotalSupply<T>>::insert(collection.id, total_supply);338339 <PalletEvm<T>>::deposit_log(340 ERC20Events::Transfer {341 from: *owner.as_eth(),342 to: H160::default(),343 value: amount.into(),344 }345 .to_log(collection_id_to_address(collection.id)),346 );347 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(348 collection.id,349 TokenId::default(),350 owner.clone(),351 amount,352 ));353 Ok(())354 }355356 357 358 359 360 361 362 363 pub fn transfer(364 collection: &FungibleHandle<T>,365 from: &T::CrossAccountId,366 to: &T::CrossAccountId,367 amount: u128,368 nesting_budget: &dyn Budget,369 ) -> DispatchResult {370 ensure!(371 collection.limits.transfers_enabled(),372 <CommonError<T>>::TransferNotAllowed,373 );374375 if collection.permissions.access() == AccessMode::AllowList {376 collection.check_allowlist(from)?;377 collection.check_allowlist(to)?;378 }379 <PalletCommon<T>>::ensure_correct_receiver(to)?;380381 let balance_from = <Balance<T>>::get((collection.id, from))382 .checked_sub(amount)383 .ok_or(<CommonError<T>>::TokenValueTooLow)?;384 let balance_to = if from != to && amount != 0 {385 Some(386 <Balance<T>>::get((collection.id, to))387 .checked_add(amount)388 .ok_or(ArithmeticError::Overflow)?,389 )390 } else {391 None392 };393394 395396 if let Some(balance_to) = balance_to {397 398399 <PalletStructure<T>>::nest_if_sent_to_token(400 from.clone(),401 to,402 collection.id,403 TokenId::default(),404 nesting_budget,405 )?;406407 if balance_from == 0 {408 <Balance<T>>::remove((collection.id, from));409 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());410 } else {411 <Balance<T>>::insert((collection.id, from), balance_from);412 }413 <Balance<T>>::insert((collection.id, to), balance_to);414 }415416 <PalletEvm<T>>::deposit_log(417 ERC20Events::Transfer {418 from: *from.as_eth(),419 to: *to.as_eth(),420 value: amount.into(),421 }422 .to_log(collection_id_to_address(collection.id)),423 );424 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(425 collection.id,426 TokenId::default(),427 from.clone(),428 to.clone(),429 amount,430 ));431 Ok(())432 }433434 435 436 437 pub fn create_multiple_items_common(438 collection: &FungibleHandle<T>,439 sender: &T::CrossAccountId,440 data: BTreeMap<T::CrossAccountId, u128>,441 nesting_budget: &dyn Budget,442 ) -> DispatchResult {443 let total_supply = data444 .iter()445 .map(|(_, v)| *v)446 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {447 acc.checked_add(v)448 })449 .ok_or(ArithmeticError::Overflow)?;450451 for (to, _) in data.iter() {452 <PalletStructure<T>>::check_nesting(453 sender.clone(),454 to,455 collection.id,456 TokenId::default(),457 nesting_budget,458 )?;459 }460461 let updated_balances = data462 .into_iter()463 .map(|(user, amount)| {464 let updated_balance = <Balance<T>>::get((collection.id, &user))465 .checked_add(amount)466 .ok_or(ArithmeticError::Overflow)?;467 Ok((user, amount, updated_balance))468 })469 .collect::<Result<Vec<_>, DispatchError>>()?;470471 472473 <TotalSupply<T>>::insert(collection.id, total_supply);474 for (user, amount, updated_balance) in updated_balances {475 <Balance<T>>::insert((collection.id, &user), updated_balance);476 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(477 &user,478 collection.id,479 TokenId::default(),480 );481 <PalletEvm<T>>::deposit_log(482 ERC20Events::Transfer {483 from: H160::default(),484 to: *user.as_eth(),485 value: amount.into(),486 }487 .to_log(collection_id_to_address(collection.id)),488 );489 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(490 collection.id,491 TokenId::default(),492 user.clone(),493 amount,494 ));495 }496497 Ok(())498 }499500 501 502 pub fn create_multiple_items(503 collection: &FungibleHandle<T>,504 sender: &T::CrossAccountId,505 data: BTreeMap<T::CrossAccountId, u128>,506 nesting_budget: &dyn Budget,507 ) -> DispatchResult {508 509 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);510511 if !collection.is_owner_or_admin(sender) {512 ensure!(513 collection.permissions.mint_mode(),514 <CommonError<T>>::PublicMintingNotAllowed515 );516 collection.check_allowlist(sender)?;517518 for (owner, _) in data.iter() {519 collection.check_allowlist(owner)?;520 }521 }522523 Self::create_multiple_items_common(collection, sender, data, nesting_budget)524 }525526 527 528 pub fn create_multiple_items_foreign(529 collection: &FungibleHandle<T>,530 sender: &T::CrossAccountId,531 data: BTreeMap<T::CrossAccountId, u128>,532 nesting_budget: &dyn Budget,533 ) -> DispatchResult {534 Self::create_multiple_items_common(collection, sender, data, nesting_budget)535 }536537 fn set_allowance_unchecked(538 collection: &FungibleHandle<T>,539 owner: &T::CrossAccountId,540 spender: &T::CrossAccountId,541 amount: u128,542 ) {543 if amount == 0 {544 <Allowance<T>>::remove((collection.id, owner, spender));545 } else {546 <Allowance<T>>::insert((collection.id, owner, spender), amount);547 }548549 <PalletEvm<T>>::deposit_log(550 ERC20Events::Approval {551 owner: *owner.as_eth(),552 spender: *spender.as_eth(),553 value: amount.into(),554 }555 .to_log(collection_id_to_address(collection.id)),556 );557 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(558 collection.id,559 TokenId(0),560 owner.clone(),561 spender.clone(),562 amount,563 ));564 }565566 567 568 569 570 571 572 pub fn set_allowance(573 collection: &FungibleHandle<T>,574 owner: &T::CrossAccountId,575 spender: &T::CrossAccountId,576 amount: u128,577 ) -> DispatchResult {578 if collection.permissions.access() == AccessMode::AllowList {579 collection.check_allowlist(owner)?;580 collection.check_allowlist(spender)?;581 }582583 if <Balance<T>>::get((collection.id, owner)) < amount {584 ensure!(585 collection.ignores_owned_amount(owner),586 <CommonError<T>>::CantApproveMoreThanOwned587 );588 }589590 591592 Self::set_allowance_unchecked(collection, owner, spender, amount);593 Ok(())594 }595596 597 598 599 600 601 602 603 fn check_allowed(604 collection: &FungibleHandle<T>,605 spender: &T::CrossAccountId,606 from: &T::CrossAccountId,607 amount: u128,608 nesting_budget: &dyn Budget,609 ) -> Result<Option<u128>, DispatchError> {610 if spender.conv_eq(from) {611 return Ok(None);612 }613 if collection.permissions.access() == AccessMode::AllowList {614 615 collection.check_allowlist(spender)?;616 }617 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {618 619 ensure!(620 <PalletStructure<T>>::check_indirectly_owned(621 spender.clone(),622 source.0,623 source.1,624 None,625 nesting_budget626 )?,627 <CommonError<T>>::ApprovedValueTooLow,628 );629 return Ok(None);630 }631 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);632 if allowance.is_none() {633 ensure!(634 collection.ignores_allowance(spender),635 <CommonError<T>>::ApprovedValueTooLow636 );637 }638639 Ok(allowance)640 }641642 643 644 645 646647 pub fn transfer_from(648 collection: &FungibleHandle<T>,649 spender: &T::CrossAccountId,650 from: &T::CrossAccountId,651 to: &T::CrossAccountId,652 amount: u128,653 nesting_budget: &dyn Budget,654 ) -> DispatchResult {655 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;656657 658659 Self::transfer(collection, from, to, amount, nesting_budget)?;660 if let Some(allowance) = allowance {661 Self::set_allowance_unchecked(collection, from, spender, allowance);662 }663 Ok(())664 }665666 667 668 669 670 671 pub fn burn_from(672 collection: &FungibleHandle<T>,673 spender: &T::CrossAccountId,674 from: &T::CrossAccountId,675 amount: u128,676 nesting_budget: &dyn Budget,677 ) -> DispatchResult {678 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;679680 681682 Self::burn(collection, from, amount)?;683 if let Some(allowance) = allowance {684 Self::set_allowance_unchecked(collection, from, spender, allowance);685 }686 Ok(())687 }688689 690 691 692 693 694 695 696 pub fn create_item(697 collection: &FungibleHandle<T>,698 sender: &T::CrossAccountId,699 data: CreateItemData<T>,700 nesting_budget: &dyn Budget,701 ) -> DispatchResult {702 Self::create_multiple_items(703 collection,704 sender,705 [(data.0, data.1)].into_iter().collect(),706 nesting_budget,707 )708 }709710 711 712 713 714 pub fn create_item_foreign(715 collection: &FungibleHandle<T>,716 sender: &T::CrossAccountId,717 data: CreateItemData<T>,718 nesting_budget: &dyn Budget,719 ) -> DispatchResult {720 Self::create_multiple_items_foreign(721 collection,722 sender,723 [(data.0, data.1)].into_iter().collect(),724 nesting_budget,725 )726 }727728 729 730 731 732 733 734 pub fn token_owners(735 collection: CollectionId,736 _token: TokenId,737 ) -> Option<Vec<T::CrossAccountId>> {738 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))739 .map(|(owner, _amount)| owner)740 .take(10)741 .collect();742743 if res.is_empty() {744 None745 } else {746 Some(res)747 }748 }749}