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, TokenId, CreateCollectionData, mapping::TokenAddressMapping,87 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::account::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 >;170171 172 #[pallet::storage]173 pub type ForeignCollection<T: Config> =174 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = bool, QueryKind = ValueQuery>;175}176177178179pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);180181182impl<T: Config> FungibleHandle<T> {183 184 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {185 Self(inner)186 }187188 189 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {190 self.0191 }192 193 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {194 &mut self.0195 }196}197impl<T: Config> WithRecorder<T> for FungibleHandle<T> {198 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {199 self.0.recorder()200 }201 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {202 self.0.into_recorder()203 }204}205impl<T: Config> Deref for FungibleHandle<T> {206 type Target = pallet_common::CollectionHandle<T>;207208 fn deref(&self) -> &Self::Target {209 &self.0210 }211}212213214impl<T: Config> Pallet<T> {215 216 pub fn init_collection(217 owner: T::CrossAccountId,218 data: CreateCollectionData<T::AccountId>,219 ) -> Result<CollectionId, DispatchError> {220 <PalletCommon<T>>::init_collection(owner, data, false)221 }222223 224 pub fn init_foreign_collection(225 owner: T::CrossAccountId,226 data: CreateCollectionData<T::AccountId>,227 ) -> Result<CollectionId, DispatchError> {228 let id = <PalletCommon<T>>::init_collection(owner, data, false)?;229 <ForeignCollection<T>>::insert(id, true);230 Ok(id)231 }232233 234 pub fn destroy_collection(235 collection: FungibleHandle<T>,236 sender: &T::CrossAccountId,237 ) -> DispatchResult {238 let id = collection.id;239240 if Self::collection_has_tokens(id) {241 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());242 }243244 245246 PalletCommon::destroy_collection(collection.0, sender)?;247248 <ForeignCollection<T>>::remove(id);249 <TotalSupply<T>>::remove(id);250 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);251 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);252 Ok(())253 }254255 256 fn collection_has_tokens(collection_id: CollectionId) -> bool {257 <TotalSupply<T>>::get(collection_id) != 0258 }259260 261 262 263 pub fn burn(264 collection: &FungibleHandle<T>,265 owner: &T::CrossAccountId,266 amount: u128,267 ) -> DispatchResult {268 let total_supply = <TotalSupply<T>>::get(collection.id)269 .checked_sub(amount)270 .ok_or(<CommonError<T>>::TokenValueTooLow)?;271272 let balance = <Balance<T>>::get((collection.id, owner))273 .checked_sub(amount)274 .ok_or(<CommonError<T>>::TokenValueTooLow)?;275276 277 ensure!(278 !<ForeignCollection<T>>::get(collection.id),279 <CommonError<T>>::NoPermission280 );281282 if collection.permissions.access() == AccessMode::AllowList {283 collection.check_allowlist(owner)?;284 }285286 287288 if balance == 0 {289 <Balance<T>>::remove((collection.id, owner));290 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());291 } else {292 <Balance<T>>::insert((collection.id, owner), balance);293 }294 <TotalSupply<T>>::insert(collection.id, total_supply);295296 <PalletEvm<T>>::deposit_log(297 ERC20Events::Transfer {298 from: *owner.as_eth(),299 to: H160::default(),300 value: amount.into(),301 }302 .to_log(collection_id_to_address(collection.id)),303 );304 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(305 collection.id,306 TokenId::default(),307 owner.clone(),308 amount,309 ));310 Ok(())311 }312313 314 pub fn burn_foreign(315 collection: &FungibleHandle<T>,316 owner: &T::CrossAccountId,317 amount: u128,318 ) -> DispatchResult {319 let total_supply = <TotalSupply<T>>::get(collection.id)320 .checked_sub(amount)321 .ok_or(<CommonError<T>>::TokenValueTooLow)?;322323 let balance = <Balance<T>>::get((collection.id, owner))324 .checked_sub(amount)325 .ok_or(<CommonError<T>>::TokenValueTooLow)?;326 327328 if balance == 0 {329 <Balance<T>>::remove((collection.id, owner));330 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());331 } else {332 <Balance<T>>::insert((collection.id, owner), balance);333 }334 <TotalSupply<T>>::insert(collection.id, total_supply);335336 <PalletEvm<T>>::deposit_log(337 ERC20Events::Transfer {338 from: *owner.as_eth(),339 to: H160::default(),340 value: amount.into(),341 }342 .to_log(collection_id_to_address(collection.id)),343 );344 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(345 collection.id,346 TokenId::default(),347 owner.clone(),348 amount,349 ));350 Ok(())351 }352353 354 355 356 357 358 359 360 pub fn transfer(361 collection: &FungibleHandle<T>,362 from: &T::CrossAccountId,363 to: &T::CrossAccountId,364 amount: u128,365 nesting_budget: &dyn Budget,366 ) -> DispatchResult {367 ensure!(368 collection.limits.transfers_enabled(),369 <CommonError<T>>::TransferNotAllowed,370 );371372 if collection.permissions.access() == AccessMode::AllowList {373 collection.check_allowlist(from)?;374 collection.check_allowlist(to)?;375 }376 <PalletCommon<T>>::ensure_correct_receiver(to)?;377378 let balance_from = <Balance<T>>::get((collection.id, from))379 .checked_sub(amount)380 .ok_or(<CommonError<T>>::TokenValueTooLow)?;381 let balance_to = if from != to {382 Some(383 <Balance<T>>::get((collection.id, to))384 .checked_add(amount)385 .ok_or(ArithmeticError::Overflow)?,386 )387 } else {388 None389 };390391 392393 <PalletStructure<T>>::nest_if_sent_to_token(394 from.clone(),395 to,396 collection.id,397 TokenId::default(),398 nesting_budget,399 )?;400401 if let Some(balance_to) = balance_to {402 403 if balance_from == 0 {404 <Balance<T>>::remove((collection.id, from));405 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());406 } else {407 <Balance<T>>::insert((collection.id, from), balance_from);408 }409 <Balance<T>>::insert((collection.id, to), balance_to);410 }411412 <PalletEvm<T>>::deposit_log(413 ERC20Events::Transfer {414 from: *from.as_eth(),415 to: *to.as_eth(),416 value: amount.into(),417 }418 .to_log(collection_id_to_address(collection.id)),419 );420 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(421 collection.id,422 TokenId::default(),423 from.clone(),424 to.clone(),425 amount,426 ));427 Ok(())428 }429430 431 432 433 pub fn create_multiple_items_common(434 collection: &FungibleHandle<T>,435 sender: &T::CrossAccountId,436 data: BTreeMap<T::CrossAccountId, u128>,437 nesting_budget: &dyn Budget,438 ) -> DispatchResult {439 let total_supply = data440 .iter()441 .map(|(_, v)| *v)442 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {443 acc.checked_add(v)444 })445 .ok_or(ArithmeticError::Overflow)?;446447 for (to, _) in data.iter() {448 <PalletStructure<T>>::check_nesting(449 sender.clone(),450 to,451 collection.id,452 TokenId::default(),453 nesting_budget,454 )?;455 }456457 let updated_balances = data458 .into_iter()459 .map(|(user, amount)| {460 let updated_balance = <Balance<T>>::get((collection.id, &user))461 .checked_add(amount)462 .ok_or(ArithmeticError::Overflow)?;463 Ok((user, amount, updated_balance))464 })465 .collect::<Result<Vec<_>, DispatchError>>()?;466467 468469 <TotalSupply<T>>::insert(collection.id, total_supply);470 for (user, amount, updated_balance) in updated_balances {471 <Balance<T>>::insert((collection.id, &user), updated_balance);472 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(473 &user,474 collection.id,475 TokenId::default(),476 );477 <PalletEvm<T>>::deposit_log(478 ERC20Events::Transfer {479 from: H160::default(),480 to: *user.as_eth(),481 value: amount.into(),482 }483 .to_log(collection_id_to_address(collection.id)),484 );485 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(486 collection.id,487 TokenId::default(),488 user.clone(),489 amount,490 ));491 }492493 Ok(())494 }495496 497 498 pub fn create_multiple_items(499 collection: &FungibleHandle<T>,500 sender: &T::CrossAccountId,501 data: BTreeMap<T::CrossAccountId, u128>,502 nesting_budget: &dyn Budget,503 ) -> DispatchResult {504 505 ensure!(506 !<ForeignCollection<T>>::get(collection.id),507 <CommonError<T>>::NoPermission508 );509510 if !collection.is_owner_or_admin(sender) {511 ensure!(512 collection.permissions.mint_mode(),513 <CommonError<T>>::PublicMintingNotAllowed514 );515 collection.check_allowlist(sender)?;516517 for (owner, _) in data.iter() {518 collection.check_allowlist(owner)?;519 }520 }521522 Self::create_multiple_items_common(collection, sender, data, nesting_budget)523 }524525 526 527 pub fn create_multiple_items_foreign(528 collection: &FungibleHandle<T>,529 sender: &T::CrossAccountId,530 data: BTreeMap<T::CrossAccountId, u128>,531 nesting_budget: &dyn Budget,532 ) -> DispatchResult {533 Self::create_multiple_items_common(collection, sender, data, nesting_budget)534 }535536 fn set_allowance_unchecked(537 collection: &FungibleHandle<T>,538 owner: &T::CrossAccountId,539 spender: &T::CrossAccountId,540 amount: u128,541 ) {542 if amount == 0 {543 <Allowance<T>>::remove((collection.id, owner, spender));544 } else {545 <Allowance<T>>::insert((collection.id, owner, spender), amount);546 }547548 <PalletEvm<T>>::deposit_log(549 ERC20Events::Approval {550 owner: *owner.as_eth(),551 spender: *spender.as_eth(),552 value: amount.into(),553 }554 .to_log(collection_id_to_address(collection.id)),555 );556 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(557 collection.id,558 TokenId(0),559 owner.clone(),560 spender.clone(),561 amount,562 ));563 }564565 566 567 568 569 570 571 pub fn set_allowance(572 collection: &FungibleHandle<T>,573 owner: &T::CrossAccountId,574 spender: &T::CrossAccountId,575 amount: u128,576 ) -> DispatchResult {577 if collection.permissions.access() == AccessMode::AllowList {578 collection.check_allowlist(owner)?;579 collection.check_allowlist(spender)?;580 }581582 if <Balance<T>>::get((collection.id, owner)) < amount {583 ensure!(584 collection.ignores_owned_amount(owner),585 <CommonError<T>>::CantApproveMoreThanOwned586 );587 }588589 590591 Self::set_allowance_unchecked(collection, owner, spender, amount);592 Ok(())593 }594595 596 597 598 599 600 601 602 fn check_allowed(603 collection: &FungibleHandle<T>,604 spender: &T::CrossAccountId,605 from: &T::CrossAccountId,606 amount: u128,607 nesting_budget: &dyn Budget,608 ) -> Result<Option<u128>, DispatchError> {609 if spender.conv_eq(from) {610 return Ok(None);611 }612 if collection.permissions.access() == AccessMode::AllowList {613 614 collection.check_allowlist(spender)?;615 }616 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {617 618 ensure!(619 <PalletStructure<T>>::check_indirectly_owned(620 spender.clone(),621 source.0,622 source.1,623 None,624 nesting_budget625 )?,626 <CommonError<T>>::ApprovedValueTooLow,627 );628 return Ok(None);629 }630 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);631 if allowance.is_none() {632 ensure!(633 collection.ignores_allowance(spender),634 <CommonError<T>>::ApprovedValueTooLow635 );636 }637638 Ok(allowance)639 }640641 642 643 644 645646 pub fn transfer_from(647 collection: &FungibleHandle<T>,648 spender: &T::CrossAccountId,649 from: &T::CrossAccountId,650 to: &T::CrossAccountId,651 amount: u128,652 nesting_budget: &dyn Budget,653 ) -> DispatchResult {654 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;655656 657658 Self::transfer(collection, from, to, amount, nesting_budget)?;659 if let Some(allowance) = allowance {660 Self::set_allowance_unchecked(collection, from, spender, allowance);661 }662 Ok(())663 }664665 666 667 668 669 670 pub fn burn_from(671 collection: &FungibleHandle<T>,672 spender: &T::CrossAccountId,673 from: &T::CrossAccountId,674 amount: u128,675 nesting_budget: &dyn Budget,676 ) -> DispatchResult {677 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;678679 680681 Self::burn(collection, from, amount)?;682 if let Some(allowance) = allowance {683 Self::set_allowance_unchecked(collection, from, spender, allowance);684 }685 Ok(())686 }687688 689 690 691 692 693 694 695 pub fn create_item(696 collection: &FungibleHandle<T>,697 sender: &T::CrossAccountId,698 data: CreateItemData<T>,699 nesting_budget: &dyn Budget,700 ) -> DispatchResult {701 Self::create_multiple_items(702 collection,703 sender,704 [(data.0, data.1)].into_iter().collect(),705 nesting_budget,706 )707 }708709 710 711 712 713 pub fn create_item_foreign(714 collection: &FungibleHandle<T>,715 sender: &T::CrossAccountId,716 data: CreateItemData<T>,717 nesting_budget: &dyn Budget,718 ) -> DispatchResult {719 Self::create_multiple_items_foreign(720 collection,721 sender,722 [(data.0, data.1)].into_iter().collect(),723 nesting_budget,724 )725 }726727 728 729 730 731 732 733 pub fn token_owners(734 collection: CollectionId,735 _token: TokenId,736 ) -> Option<Vec<T::CrossAccountId>> {737 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))738 .map(|(owner, _amount)| owner)739 .take(10)740 .collect();741742 if res.is_empty() {743 None744 } else {745 Some(res)746 }747 }748}