12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879#![cfg_attr(not(feature = "std"), no_std)]8081use core::ops::Deref;8283use evm_coder::ToLog;84use frame_support::{dispatch::PostDispatchInfo, ensure, pallet_prelude::*};85pub use pallet::*;86use pallet_common::{87 eth::collection_id_to_address, helpers::add_weight_to_post_info,88 weights::WeightInfo as CommonWeightInfo, Error as CommonError, Event as CommonEvent,89 Pallet as PalletCommon, SelfWeightOf as PalletCommonWeightOf,90};91use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};92use pallet_evm_coder_substrate::WithRecorder;93use pallet_structure::Pallet as PalletStructure;94use sp_core::H160;95use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};96use sp_std::{collections::btree_map::BTreeMap, vec::Vec};97use up_data_structs::{98 budget::{Budget, ZeroBudget},99 mapping::TokenAddressMapping,100 AccessMode, CollectionId, CreateCollectionData, Property, PropertyKey, TokenId,101};102use weights::WeightInfo;103104use crate::erc::ERC20Events;105#[cfg(feature = "runtime-benchmarks")]106pub mod benchmarking;107pub mod common;108pub mod erc;109pub mod weights;110111pub type CreateItemData<T> = (<T as pallet_evm::Config>::CrossAccountId, u128);112pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;113114#[frame_support::pallet]115pub mod pallet {116 use frame_support::{117 pallet_prelude::*, storage::Key, Blake2_128, Blake2_128Concat, Twox64Concat,118 };119 use up_data_structs::CollectionId;120121 use super::weights::WeightInfo;122123 #[pallet::error]124 pub enum Error<T> {125 126 FungibleItemsDontHaveData,127 128 FungibleDisallowsNesting,129 130 SettingPropertiesNotAllowed,131 132 SettingAllowanceForAllNotAllowed,133 134 FungibleTokensAreAlwaysValid,135 }136137 #[pallet::config]138 pub trait Config:139 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config140 {141 type WeightInfo: WeightInfo;142 }143144 #[pallet::pallet]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 destroy_collection(216 collection: FungibleHandle<T>,217 sender: &T::CrossAccountId,218 ) -> DispatchResult {219 let id = collection.id;220221 if Self::collection_has_tokens(id) {222 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());223 }224225 226227 PalletCommon::destroy_collection(collection.0, sender)?;228229 <TotalSupply<T>>::remove(id);230 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);231 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);232 Ok(())233 }234235 236 pub fn set_collection_properties(237 collection: &FungibleHandle<T>,238 sender: &T::CrossAccountId,239 properties: Vec<Property>,240 ) -> DispatchResult {241 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())242 }243244 245 pub fn delete_collection_properties(246 collection: &FungibleHandle<T>,247 sender: &T::CrossAccountId,248 property_keys: Vec<PropertyKey>,249 ) -> DispatchResult {250 <PalletCommon<T>>::delete_collection_properties(251 collection,252 sender,253 property_keys.into_iter(),254 )255 }256257 258 fn collection_has_tokens(collection_id: CollectionId) -> bool {259 <TotalSupply<T>>::get(collection_id) != 0260 }261262 263 264 265 pub fn burn(266 collection: &FungibleHandle<T>,267 owner: &T::CrossAccountId,268 amount: u128,269 ) -> DispatchResult {270 let total_supply = <TotalSupply<T>>::get(collection.id)271 .checked_sub(amount)272 .ok_or(<CommonError<T>>::TokenValueTooLow)?;273274 let balance = <Balance<T>>::get((collection.id, owner))275 .checked_sub(amount)276 .ok_or(<CommonError<T>>::TokenValueTooLow)?;277278 if collection.permissions.access() == AccessMode::AllowList {279 collection.check_allowlist(owner)?;280 }281282 283284 if balance == 0 {285 <Balance<T>>::remove((collection.id, owner));286 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());287 } else {288 <Balance<T>>::insert((collection.id, owner), balance);289 }290 <TotalSupply<T>>::insert(collection.id, total_supply);291292 <PalletEvm<T>>::deposit_log(293 ERC20Events::Transfer {294 from: *owner.as_eth(),295 to: H160::default(),296 value: amount.into(),297 }298 .to_log(collection_id_to_address(collection.id)),299 );300 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(301 collection.id,302 TokenId::default(),303 owner.clone(),304 amount,305 ));306 Ok(())307 }308309 310 311 312 313 314 315 316 pub fn transfer(317 collection: &FungibleHandle<T>,318 from: &T::CrossAccountId,319 to: &T::CrossAccountId,320 amount: u128,321 nesting_budget: &dyn Budget,322 ) -> DispatchResultWithPostInfo {323 let depositor = from;324 Self::transfer_internal(collection, depositor, from, to, amount, nesting_budget)325 }326327 328 329 330 fn transfer_internal(331 collection: &FungibleHandle<T>,332 depositor: &T::CrossAccountId,333 from: &T::CrossAccountId,334 to: &T::CrossAccountId,335 amount: u128,336 nesting_budget: &dyn Budget,337 ) -> DispatchResultWithPostInfo {338 ensure!(339 collection.limits.transfers_enabled(),340 <CommonError<T>>::TransferNotAllowed,341 );342343 let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();344345 if collection.permissions.access() == AccessMode::AllowList {346 collection.check_allowlist(from)?;347 collection.check_allowlist(to)?;348 actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;349 }350 <PalletCommon<T>>::ensure_correct_receiver(to)?;351 let balance_from = <Balance<T>>::get((collection.id, from))352 .checked_sub(amount)353 .ok_or(<CommonError<T>>::TokenValueTooLow)?;354 let balance_to = if from != to && amount != 0 {355 Some(356 <Balance<T>>::get((collection.id, to))357 .checked_add(amount)358 .ok_or(ArithmeticError::Overflow)?,359 )360 } else {361 None362 };363364 365366 if let Some(balance_to) = balance_to {367 368369 <PalletStructure<T>>::nest_if_sent_to_token(370 depositor,371 to,372 collection.id,373 TokenId::default(),374 nesting_budget,375 )?;376377 if balance_from == 0 {378 <Balance<T>>::remove((collection.id, from));379 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());380 } else {381 <Balance<T>>::insert((collection.id, from), balance_from);382 }383 <Balance<T>>::insert((collection.id, to), balance_to);384 }385386 <PalletEvm<T>>::deposit_log(387 ERC20Events::Transfer {388 from: *from.as_eth(),389 to: *to.as_eth(),390 value: amount.into(),391 }392 .to_log(collection_id_to_address(collection.id)),393 );394 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(395 collection.id,396 TokenId::default(),397 from.clone(),398 to.clone(),399 amount,400 ));401402 Ok(PostDispatchInfo {403 actual_weight: Some(actual_weight),404 pays_fee: Pays::Yes,405 })406 }407408 409 410 pub fn create_multiple_items(411 collection: &FungibleHandle<T>,412 depositor: &T::CrossAccountId,413 data: BTreeMap<T::CrossAccountId, u128>,414 nesting_budget: &dyn Budget,415 ) -> DispatchResult {416 if !collection.is_owner_or_admin(depositor) {417 ensure!(418 collection.permissions.mint_mode(),419 <CommonError<T>>::PublicMintingNotAllowed420 );421 collection.check_allowlist(depositor)?;422423 for (owner, _) in data.iter() {424 collection.check_allowlist(owner)?;425 }426 }427428 let total_supply = data429 .values()430 .copied()431 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {432 acc.checked_add(v)433 })434 .ok_or(ArithmeticError::Overflow)?;435436 for (to, _) in data.iter() {437 <PalletStructure<T>>::check_nesting(438 depositor,439 to,440 collection.id,441 TokenId::default(),442 nesting_budget,443 )?;444 }445446 let updated_balances = data447 .into_iter()448 .map(|(user, amount)| {449 let updated_balance = <Balance<T>>::get((collection.id, &user))450 .checked_add(amount)451 .ok_or(ArithmeticError::Overflow)?;452 Ok((user, amount, updated_balance))453 })454 .collect::<Result<Vec<_>, DispatchError>>()?;455456 457458 <TotalSupply<T>>::insert(collection.id, total_supply);459 for (user, amount, updated_balance) in updated_balances {460 <Balance<T>>::insert((collection.id, &user), updated_balance);461 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(462 &user,463 collection.id,464 TokenId::default(),465 );466 <PalletEvm<T>>::deposit_log(467 ERC20Events::Transfer {468 from: H160::default(),469 to: *user.as_eth(),470 value: amount.into(),471 }472 .to_log(collection_id_to_address(collection.id)),473 );474 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(475 collection.id,476 TokenId::default(),477 user.clone(),478 amount,479 ));480 }481482 Ok(())483 }484485 fn set_allowance_unchecked(486 collection: &FungibleHandle<T>,487 owner: &T::CrossAccountId,488 spender: &T::CrossAccountId,489 amount: u128,490 ) {491 if amount == 0 {492 <Allowance<T>>::remove((collection.id, owner, spender));493 } else {494 <Allowance<T>>::insert((collection.id, owner, spender), amount);495 }496497 <PalletEvm<T>>::deposit_log(498 ERC20Events::Approval {499 owner: *owner.as_eth(),500 spender: *spender.as_eth(),501 value: amount.into(),502 }503 .to_log(collection_id_to_address(collection.id)),504 );505 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(506 collection.id,507 TokenId(0),508 owner.clone(),509 spender.clone(),510 amount,511 ));512 }513514 515 516 517 518 519 520 pub fn set_allowance(521 collection: &FungibleHandle<T>,522 owner: &T::CrossAccountId,523 spender: &T::CrossAccountId,524 amount: u128,525 ) -> DispatchResult {526 if collection.permissions.access() == AccessMode::AllowList {527 collection.check_allowlist(owner)?;528 collection.check_allowlist(spender)?;529 }530531 if <Balance<T>>::get((collection.id, owner)) < amount {532 ensure!(533 collection.ignores_owned_amount(owner),534 <CommonError<T>>::CantApproveMoreThanOwned535 );536 }537538 539540 Self::set_allowance_unchecked(collection, owner, spender, amount);541 Ok(())542 }543544 545 546 547 548 549 550 551 pub fn set_allowance_from(552 collection: &FungibleHandle<T>,553 sender: &T::CrossAccountId,554 from: &T::CrossAccountId,555 to: &T::CrossAccountId,556 amount: u128,557 ) -> DispatchResult {558 if collection.permissions.access() == AccessMode::AllowList {559 collection.check_allowlist(sender)?;560 collection.check_allowlist(from)?;561 collection.check_allowlist(to)?;562 }563564 ensure!(565 sender.conv_eq(from),566 <CommonError<T>>::AddressIsNotEthMirror567 );568569 if <Balance<T>>::get((collection.id, from)) < amount {570 ensure!(571 collection.limits.owner_can_transfer()572 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),573 <CommonError<T>>::CantApproveMoreThanOwned574 );575 }576577 578579 Self::set_allowance_unchecked(collection, from, to, amount);580 Ok(())581 }582583 584 585 586 587 588 589 590 fn check_allowed(591 collection: &FungibleHandle<T>,592 spender: &T::CrossAccountId,593 from: &T::CrossAccountId,594 amount: u128,595 nesting_budget: &dyn Budget,596 ) -> Result<Option<u128>, DispatchError> {597 if spender.conv_eq(from) {598 return Ok(None);599 }600 if collection.permissions.access() == AccessMode::AllowList {601 602 collection.check_allowlist(spender)?;603 }604605 if collection.ignores_token_restrictions(spender) {606 return Ok(Self::compute_allowance_decrease(607 collection, from, spender, amount,608 ));609 }610611 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {612 ensure!(613 <PalletStructure<T>>::check_indirectly_owned(614 spender.clone(),615 source.0,616 source.1,617 None,618 nesting_budget619 )?,620 <CommonError<T>>::ApprovedValueTooLow,621 );622 return Ok(None);623 }624625 let allowance = Self::compute_allowance_decrease(collection, from, spender, amount);626 ensure!(allowance.is_some(), <CommonError<T>>::ApprovedValueTooLow);627628 Ok(allowance)629 }630631 632 633 fn compute_allowance_decrease(634 collection: &FungibleHandle<T>,635 from: &T::CrossAccountId,636 spender: &T::CrossAccountId,637 amount: u128,638 ) -> Option<u128> {639 <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount)640 }641642 643 644 645 646 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 ) -> DispatchResultWithPostInfo {654 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;655656 657658 let mut result =659 Self::transfer_internal(collection, spender, from, to, amount, nesting_budget);660 add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::check_allowed_raw());661 result?;662663 if let Some(allowance) = allowance {664 Self::set_allowance_unchecked(collection, from, spender, allowance);665 add_weight_to_post_info(666 &mut result,667 <SelfWeightOf<T>>::set_allowance_unchecked_raw(),668 )669 }670 result671 }672673 674 675 676 677 678 pub fn burn_from(679 collection: &FungibleHandle<T>,680 spender: &T::CrossAccountId,681 from: &T::CrossAccountId,682 amount: u128,683 nesting_budget: &dyn Budget,684 ) -> DispatchResult {685 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;686687 688689 Self::burn(collection, from, amount)?;690 if let Some(allowance) = allowance {691 Self::set_allowance_unchecked(collection, from, spender, allowance);692 }693 Ok(())694 }695696 697 698 699 700 701 702 703 pub fn create_item(704 collection: &FungibleHandle<T>,705 sender: &T::CrossAccountId,706 data: CreateItemData<T>,707 nesting_budget: &dyn Budget,708 ) -> DispatchResult {709 Self::create_multiple_items(710 collection,711 sender,712 [(data.0, data.1)].into_iter().collect(),713 nesting_budget,714 )715 }716717 718 719 720 721 722 723 pub fn token_owners(724 collection: CollectionId,725 _token: TokenId,726 ) -> Option<Vec<T::CrossAccountId>> {727 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))728 .map(|(owner, _amount)| owner)729 .take(10)730 .collect();731732 if res.is_empty() {733 None734 } else {735 Some(res)736 }737 }738}