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, false)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 let total_supply = <TotalSupply<T>>::get(collection.id)172 .checked_sub(amount)173 .ok_or(<CommonError<T>>::TokenValueTooLow)?;174175 let balance = <Balance<T>>::get((collection.id, owner))176 .checked_sub(amount)177 .ok_or(<CommonError<T>>::TokenValueTooLow)?;178179 if collection.permissions.access() == AccessMode::AllowList {180 collection.check_allowlist(owner)?;181 }182183 184185 if balance == 0 {186 <Balance<T>>::remove((collection.id, owner));187 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());188 } else {189 <Balance<T>>::insert((collection.id, owner), balance);190 }191 <TotalSupply<T>>::insert(collection.id, total_supply);192193 <PalletEvm<T>>::deposit_log(194 ERC20Events::Transfer {195 from: *owner.as_eth(),196 to: H160::default(),197 value: amount.into(),198 }199 .to_log(collection_id_to_address(collection.id)),200 );201 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(202 collection.id,203 TokenId::default(),204 owner.clone(),205 amount,206 ));207 Ok(())208 }209210 pub fn transfer(211 collection: &FungibleHandle<T>,212 from: &T::CrossAccountId,213 to: &T::CrossAccountId,214 amount: u128,215 nesting_budget: &dyn Budget,216 ) -> DispatchResult {217 ensure!(218 collection.limits.transfers_enabled(),219 <CommonError<T>>::TransferNotAllowed,220 );221222 if collection.permissions.access() == AccessMode::AllowList {223 collection.check_allowlist(from)?;224 collection.check_allowlist(to)?;225 }226 <PalletCommon<T>>::ensure_correct_receiver(to)?;227228 let balance_from = <Balance<T>>::get((collection.id, from))229 .checked_sub(amount)230 .ok_or(<CommonError<T>>::TokenValueTooLow)?;231 let balance_to = if from != to {232 Some(233 <Balance<T>>::get((collection.id, to))234 .checked_add(amount)235 .ok_or(ArithmeticError::Overflow)?,236 )237 } else {238 None239 };240241 242243 <PalletStructure<T>>::nest_if_sent_to_token(244 from.clone(),245 to,246 collection.id,247 TokenId::default(),248 nesting_budget,249 )?;250251 if let Some(balance_to) = balance_to {252 253 if balance_from == 0 {254 <Balance<T>>::remove((collection.id, from));255 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());256 } else {257 <Balance<T>>::insert((collection.id, from), balance_from);258 }259 <Balance<T>>::insert((collection.id, to), balance_to);260 }261262 <PalletEvm<T>>::deposit_log(263 ERC20Events::Transfer {264 from: *from.as_eth(),265 to: *to.as_eth(),266 value: amount.into(),267 }268 .to_log(collection_id_to_address(collection.id)),269 );270 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(271 collection.id,272 TokenId::default(),273 from.clone(),274 to.clone(),275 amount,276 ));277 Ok(())278 }279280 pub fn create_multiple_items(281 collection: &FungibleHandle<T>,282 sender: &T::CrossAccountId,283 data: BTreeMap<T::CrossAccountId, u128>,284 nesting_budget: &dyn Budget,285 ) -> DispatchResult {286 if !collection.is_owner_or_admin(sender) {287 ensure!(288 collection.permissions.mint_mode(),289 <CommonError<T>>::PublicMintingNotAllowed290 );291 collection.check_allowlist(sender)?;292293 for (owner, _) in data.iter() {294 collection.check_allowlist(owner)?;295 }296 }297298 let total_supply = data299 .iter()300 .map(|(_, v)| *v)301 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {302 acc.checked_add(v)303 })304 .ok_or(ArithmeticError::Overflow)?;305306 let mut balances = data;307 for (k, v) in balances.iter_mut() {308 *v = <Balance<T>>::get((collection.id, &k))309 .checked_add(*v)310 .ok_or(ArithmeticError::Overflow)?;311 }312313 for (to, _) in balances.iter() {314 <PalletStructure<T>>::check_nesting(315 sender.clone(),316 to,317 collection.id,318 TokenId::default(),319 nesting_budget,320 )?;321 }322323 324325 <TotalSupply<T>>::insert(collection.id, total_supply);326 for (user, amount) in balances {327 <Balance<T>>::insert((collection.id, &user), amount);328 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(329 &user,330 collection.id,331 TokenId::default(),332 );333 <PalletEvm<T>>::deposit_log(334 ERC20Events::Transfer {335 from: H160::default(),336 to: *user.as_eth(),337 value: amount.into(),338 }339 .to_log(collection_id_to_address(collection.id)),340 );341 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(342 collection.id,343 TokenId::default(),344 user.clone(),345 amount,346 ));347 }348349 Ok(())350 }351352 fn set_allowance_unchecked(353 collection: &FungibleHandle<T>,354 owner: &T::CrossAccountId,355 spender: &T::CrossAccountId,356 amount: u128,357 ) {358 if amount == 0 {359 <Allowance<T>>::remove((collection.id, owner, spender));360 } else {361 <Allowance<T>>::insert((collection.id, owner, spender), amount);362 }363364 <PalletEvm<T>>::deposit_log(365 ERC20Events::Approval {366 owner: *owner.as_eth(),367 spender: *spender.as_eth(),368 value: amount.into(),369 }370 .to_log(collection_id_to_address(collection.id)),371 );372 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(373 collection.id,374 TokenId(0),375 owner.clone(),376 spender.clone(),377 amount,378 ));379 }380381 pub fn set_allowance(382 collection: &FungibleHandle<T>,383 owner: &T::CrossAccountId,384 spender: &T::CrossAccountId,385 amount: u128,386 ) -> DispatchResult {387 if collection.permissions.access() == AccessMode::AllowList {388 collection.check_allowlist(owner)?;389 collection.check_allowlist(spender)?;390 }391392 if <Balance<T>>::get((collection.id, owner)) < amount {393 ensure!(394 collection.ignores_owned_amount(owner),395 <CommonError<T>>::CantApproveMoreThanOwned396 );397 }398399 400401 Self::set_allowance_unchecked(collection, owner, spender, amount);402 Ok(())403 }404405 fn check_allowed(406 collection: &FungibleHandle<T>,407 spender: &T::CrossAccountId,408 from: &T::CrossAccountId,409 amount: u128,410 nesting_budget: &dyn Budget,411 ) -> Result<Option<u128>, DispatchError> {412 if spender.conv_eq(from) {413 return Ok(None);414 }415 if collection.permissions.access() == AccessMode::AllowList {416 417 collection.check_allowlist(spender)?;418 }419 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {420 421 ensure!(422 <PalletStructure<T>>::check_indirectly_owned(423 spender.clone(),424 source.0,425 source.1,426 None,427 nesting_budget428 )?,429 <CommonError<T>>::ApprovedValueTooLow,430 );431 return Ok(None);432 }433 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);434 if allowance.is_none() {435 ensure!(436 collection.ignores_allowance(spender),437 <CommonError<T>>::ApprovedValueTooLow438 );439 }440441 Ok(allowance)442 }443444 pub fn transfer_from(445 collection: &FungibleHandle<T>,446 spender: &T::CrossAccountId,447 from: &T::CrossAccountId,448 to: &T::CrossAccountId,449 amount: u128,450 nesting_budget: &dyn Budget,451 ) -> DispatchResult {452 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;453454 455456 Self::transfer(collection, from, to, amount, nesting_budget)?;457 if let Some(allowance) = allowance {458 Self::set_allowance_unchecked(collection, from, spender, allowance);459 }460 Ok(())461 }462463 pub fn burn_from(464 collection: &FungibleHandle<T>,465 spender: &T::CrossAccountId,466 from: &T::CrossAccountId,467 amount: u128,468 nesting_budget: &dyn Budget,469 ) -> DispatchResult {470 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;471472 473474 Self::burn(collection, from, amount)?;475 if let Some(allowance) = allowance {476 Self::set_allowance_unchecked(collection, from, spender, allowance);477 }478 Ok(())479 }480481 482 pub fn create_item(483 collection: &FungibleHandle<T>,484 sender: &T::CrossAccountId,485 data: CreateItemData<T>,486 nesting_budget: &dyn Budget,487 ) -> DispatchResult {488 Self::create_multiple_items(489 collection,490 sender,491 [(data.0, data.1)].into_iter().collect(),492 nesting_budget,493 )494 }495}