1234567891011121314151617#![cfg_attr(not(feature = "std"), no_std)]1819use core::ops::Deref;20use evm_coder::ToLog;21use frame_support::{ensure};22use pallet_evm::account::CrossAccountId;23use up_data_structs::{24 AccessMode, CollectionId, TokenId, CreateCollectionData, mapping::TokenAddressMapping,25 budget::Budget,26};27use pallet_common::{28 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,29 eth::collection_id_to_address,30};31use pallet_evm::Pallet as PalletEvm;32use pallet_structure::Pallet as PalletStructure;33use pallet_evm_coder_substrate::WithRecorder;34use sp_core::H160;35use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};36use sp_std::{collections::btree_map::BTreeMap};3738pub use pallet::*;3940use crate::erc::ERC20Events;41#[cfg(feature = "runtime-benchmarks")]42pub mod benchmarking;43pub mod common;44pub mod erc;45pub mod weights;4647pub type CreateItemData<T> = (<T as pallet_evm::account::Config>::CrossAccountId, u128);48pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4950#[frame_support::pallet]51pub mod pallet {52 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};53 use up_data_structs::CollectionId;54 use super::weights::WeightInfo;5556 #[pallet::error]57 pub enum Error<T> {58 59 NotFungibleDataUsedToMintFungibleCollectionToken,60 61 FungibleItemsHaveNoId,62 63 FungibleItemsDontHaveData,64 65 FungibleDisallowsNesting,66 67 SettingPropertiesNotAllowed,68 }6970 #[pallet::config]71 pub trait Config:72 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config73 {74 type WeightInfo: WeightInfo;75 }7677 #[pallet::pallet]78 #[pallet::generate_store(pub(super) trait Store)]79 pub struct Pallet<T>(_);8081 #[pallet::storage]82 pub type TotalSupply<T: Config> =83 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;8485 #[pallet::storage]86 pub type Balance<T: Config> = StorageNMap<87 Key = (88 Key<Twox64Concat, CollectionId>,89 Key<Blake2_128Concat, T::CrossAccountId>,90 ),91 Value = u128,92 QueryKind = ValueQuery,93 >;9495 #[pallet::storage]96 pub type Allowance<T: Config> = StorageNMap<97 Key = (98 Key<Twox64Concat, CollectionId>,99 Key<Blake2_128, T::CrossAccountId>,100 Key<Blake2_128Concat, T::CrossAccountId>,101 ),102 Value = u128,103 QueryKind = ValueQuery,104 >;105}106107pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);108impl<T: Config> FungibleHandle<T> {109 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {110 Self(inner)111 }112 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {113 self.0114 }115 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {116 &mut self.0117 }118}119impl<T: Config> WithRecorder<T> for FungibleHandle<T> {120 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {121 self.0.recorder()122 }123 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {124 self.0.into_recorder()125 }126}127impl<T: Config> Deref for FungibleHandle<T> {128 type Target = pallet_common::CollectionHandle<T>;129130 fn deref(&self) -> &Self::Target {131 &self.0132 }133}134135impl<T: Config> Pallet<T> {136 pub fn init_collection(137 owner: T::CrossAccountId,138 data: CreateCollectionData<T::AccountId>,139 ) -> Result<CollectionId, DispatchError> {140 <PalletCommon<T>>::init_collection(owner, data)141 }142 pub fn destroy_collection(143 collection: FungibleHandle<T>,144 sender: &T::CrossAccountId,145 ) -> DispatchResult {146 let id = collection.id;147148 if Self::collection_has_tokens(id) {149 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());150 }151152 153154 PalletCommon::destroy_collection(collection.0, sender)?;155156 <TotalSupply<T>>::remove(id);157 <Balance<T>>::remove_prefix((id,), None);158 <Allowance<T>>::remove_prefix((id,), None);159 Ok(())160 }161162 fn collection_has_tokens(collection_id: CollectionId) -> bool {163 <TotalSupply<T>>::get(collection_id) != 0164 }165166 pub fn burn(167 collection: &FungibleHandle<T>,168 owner: &T::CrossAccountId,169 amount: u128,170 ) -> DispatchResult {171 collection.check_is_mutable()?;172173 let total_supply = <TotalSupply<T>>::get(collection.id)174 .checked_sub(amount)175 .ok_or(<CommonError<T>>::TokenValueTooLow)?;176177 let balance = <Balance<T>>::get((collection.id, owner))178 .checked_sub(amount)179 .ok_or(<CommonError<T>>::TokenValueTooLow)?;180181 if collection.permissions.access() == AccessMode::AllowList {182 collection.check_allowlist(owner)?;183 }184185 186187 if balance == 0 {188 <Balance<T>>::remove((collection.id, owner));189 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());190 } else {191 <Balance<T>>::insert((collection.id, owner), balance);192 }193 <TotalSupply<T>>::insert(collection.id, total_supply);194195 <PalletEvm<T>>::deposit_log(196 ERC20Events::Transfer {197 from: *owner.as_eth(),198 to: H160::default(),199 value: amount.into(),200 }201 .to_log(collection_id_to_address(collection.id)),202 );203 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(204 collection.id,205 TokenId::default(),206 owner.clone(),207 amount,208 ));209 Ok(())210 }211212 pub fn transfer(213 collection: &FungibleHandle<T>,214 from: &T::CrossAccountId,215 to: &T::CrossAccountId,216 amount: u128,217 nesting_budget: &dyn Budget,218 ) -> DispatchResult {219 collection.check_is_mutable()?;220221 ensure!(222 collection.limits.transfers_enabled(),223 <CommonError<T>>::TransferNotAllowed,224 );225226 if collection.permissions.access() == AccessMode::AllowList {227 collection.check_allowlist(from)?;228 collection.check_allowlist(to)?;229 }230 <PalletCommon<T>>::ensure_correct_receiver(to)?;231232 let balance_from = <Balance<T>>::get((collection.id, from))233 .checked_sub(amount)234 .ok_or(<CommonError<T>>::TokenValueTooLow)?;235 let balance_to = if from != to {236 Some(237 <Balance<T>>::get((collection.id, to))238 .checked_add(amount)239 .ok_or(ArithmeticError::Overflow)?,240 )241 } else {242 None243 };244245 246247 <PalletStructure<T>>::nest_if_sent_to_token(248 from.clone(),249 to,250 collection.id,251 TokenId::default(),252 nesting_budget,253 )?;254255 if let Some(balance_to) = balance_to {256 257 if balance_from == 0 {258 <Balance<T>>::remove((collection.id, from));259 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());260 } else {261 <Balance<T>>::insert((collection.id, from), balance_from);262 }263 <Balance<T>>::insert((collection.id, to), balance_to);264 }265266 <PalletEvm<T>>::deposit_log(267 ERC20Events::Transfer {268 from: *from.as_eth(),269 to: *to.as_eth(),270 value: amount.into(),271 }272 .to_log(collection_id_to_address(collection.id)),273 );274 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(275 collection.id,276 TokenId::default(),277 from.clone(),278 to.clone(),279 amount,280 ));281 Ok(())282 }283284 pub fn create_multiple_items(285 collection: &FungibleHandle<T>,286 sender: &T::CrossAccountId,287 data: BTreeMap<T::CrossAccountId, u128>,288 nesting_budget: &dyn Budget,289 ) -> DispatchResult {290 collection.check_is_mutable()?;291292 if !collection.is_owner_or_admin(sender) {293 ensure!(294 collection.permissions.mint_mode(),295 <CommonError<T>>::PublicMintingNotAllowed296 );297 collection.check_allowlist(sender)?;298299 for (owner, _) in data.iter() {300 collection.check_allowlist(owner)?;301 }302 }303304 let total_supply = data305 .iter()306 .map(|(_, v)| *v)307 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {308 acc.checked_add(v)309 })310 .ok_or(ArithmeticError::Overflow)?;311312 let mut balances = data;313 for (k, v) in balances.iter_mut() {314 *v = <Balance<T>>::get((collection.id, &k))315 .checked_add(*v)316 .ok_or(ArithmeticError::Overflow)?;317 }318319 for (to, _) in balances.iter() {320 <PalletStructure<T>>::check_nesting(321 sender.clone(),322 to,323 collection.id,324 TokenId::default(),325 nesting_budget,326 )?;327 }328329 330331 <TotalSupply<T>>::insert(collection.id, total_supply);332 for (user, amount) in balances {333 <Balance<T>>::insert((collection.id, &user), amount);334 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(335 &user,336 collection.id,337 TokenId::default(),338 );339 <PalletEvm<T>>::deposit_log(340 ERC20Events::Transfer {341 from: H160::default(),342 to: *user.as_eth(),343 value: amount.into(),344 }345 .to_log(collection_id_to_address(collection.id)),346 );347 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(348 collection.id,349 TokenId::default(),350 user.clone(),351 amount,352 ));353 }354355 Ok(())356 }357358 fn set_allowance_unchecked(359 collection: &FungibleHandle<T>,360 owner: &T::CrossAccountId,361 spender: &T::CrossAccountId,362 amount: u128,363 ) {364 if amount == 0 {365 <Allowance<T>>::remove((collection.id, owner, spender));366 } else {367 <Allowance<T>>::insert((collection.id, owner, spender), amount);368 }369370 <PalletEvm<T>>::deposit_log(371 ERC20Events::Approval {372 owner: *owner.as_eth(),373 spender: *spender.as_eth(),374 value: amount.into(),375 }376 .to_log(collection_id_to_address(collection.id)),377 );378 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(379 collection.id,380 TokenId(0),381 owner.clone(),382 spender.clone(),383 amount,384 ));385 }386387 pub fn set_allowance(388 collection: &FungibleHandle<T>,389 owner: &T::CrossAccountId,390 spender: &T::CrossAccountId,391 amount: u128,392 ) -> DispatchResult {393 collection.check_is_mutable()?;394 if collection.permissions.access() == AccessMode::AllowList {395 collection.check_allowlist(owner)?;396 collection.check_allowlist(spender)?;397 }398399 if <Balance<T>>::get((collection.id, owner)) < amount {400 ensure!(401 collection.ignores_owned_amount(owner),402 <CommonError<T>>::CantApproveMoreThanOwned403 );404 }405406 407408 Self::set_allowance_unchecked(collection, owner, spender, amount);409 Ok(())410 }411412 fn check_allowed(413 collection: &FungibleHandle<T>,414 spender: &T::CrossAccountId,415 from: &T::CrossAccountId,416 amount: u128,417 nesting_budget: &dyn Budget,418 ) -> Result<Option<u128>, DispatchError> {419 if spender.conv_eq(from) {420 return Ok(None);421 }422 if collection.permissions.access() == AccessMode::AllowList {423 424 collection.check_allowlist(spender)?;425 }426 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {427 428 ensure!(429 <PalletStructure<T>>::check_indirectly_owned(430 spender.clone(),431 source.0,432 source.1,433 None,434 nesting_budget435 )?,436 <CommonError<T>>::ApprovedValueTooLow,437 );438 return Ok(None);439 }440 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);441 if allowance.is_none() {442 ensure!(443 collection.ignores_allowance(spender),444 <CommonError<T>>::ApprovedValueTooLow445 );446 }447448 Ok(allowance)449 }450451 pub fn transfer_from(452 collection: &FungibleHandle<T>,453 spender: &T::CrossAccountId,454 from: &T::CrossAccountId,455 to: &T::CrossAccountId,456 amount: u128,457 nesting_budget: &dyn Budget,458 ) -> DispatchResult {459 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;460461 462463 Self::transfer(collection, from, to, amount, nesting_budget)?;464 if let Some(allowance) = allowance {465 Self::set_allowance_unchecked(collection, from, spender, allowance);466 }467 Ok(())468 }469470 pub fn burn_from(471 collection: &FungibleHandle<T>,472 spender: &T::CrossAccountId,473 from: &T::CrossAccountId,474 amount: u128,475 nesting_budget: &dyn Budget,476 ) -> DispatchResult {477 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;478479 480481 Self::burn(collection, from, amount)?;482 if let Some(allowance) = allowance {483 Self::set_allowance_unchecked(collection, from, spender, allowance);484 }485 Ok(())486 }487488 489 pub fn create_item(490 collection: &FungibleHandle<T>,491 sender: &T::CrossAccountId,492 data: CreateItemData<T>,493 nesting_budget: &dyn Budget,494 ) -> DispatchResult {495 Self::create_multiple_items(496 collection,497 sender,498 [(data.0, data.1)].into_iter().collect(),499 nesting_budget,500 )501 }502}