1234567891011121314151617#![cfg_attr(not(feature = "std"), no_std)]1819use core::ops::Deref;20use frame_support::{ensure};21use pallet_evm::account::CrossAccountId;22use up_data_structs::{23 AccessMode, CollectionId, TokenId, CreateCollectionData, mapping::TokenAddressMapping,24 budget::Budget,25};26use pallet_common::{27 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, CollectionHandle,28 dispatch::CollectionDispatch,29};30use pallet_structure::Pallet as PalletStructure;31use pallet_evm_coder_substrate::WithRecorder;32use sp_core::H160;33use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};34use sp_std::collections::btree_map::BTreeMap;3536pub use pallet::*;3738use crate::erc::ERC20Events;39#[cfg(feature = "runtime-benchmarks")]40pub mod benchmarking;41pub mod common;42pub mod erc;43pub mod weights;4445pub type CreateItemData<T> = (<T as pallet_evm::account::Config>::CrossAccountId, u128);46pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4748#[frame_support::pallet]49pub mod pallet {50 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};51 use up_data_structs::CollectionId;52 use super::weights::WeightInfo;5354 #[pallet::error]55 pub enum Error<T> {56 57 NotFungibleDataUsedToMintFungibleCollectionToken,58 59 FungibleItemsHaveNoId,60 61 FungibleItemsDontHaveData,62 63 FungibleDisallowsNesting,64 }6566 #[pallet::config]67 pub trait Config:68 frame_system::Config + pallet_common::Config + pallet_structure::Config69 {70 type WeightInfo: WeightInfo;71 }7273 #[pallet::pallet]74 #[pallet::generate_store(pub(super) trait Store)]75 pub struct Pallet<T>(_);7677 #[pallet::storage]78 pub type TotalSupply<T: Config> =79 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;8081 #[pallet::storage]82 pub type Balance<T: Config> = StorageNMap<83 Key = (84 Key<Twox64Concat, CollectionId>,85 Key<Blake2_128Concat, T::CrossAccountId>,86 ),87 Value = u128,88 QueryKind = ValueQuery,89 >;9091 #[pallet::storage]92 pub type Allowance<T: Config> = StorageNMap<93 Key = (94 Key<Twox64Concat, CollectionId>,95 Key<Blake2_128, T::CrossAccountId>,96 Key<Blake2_128Concat, T::CrossAccountId>,97 ),98 Value = u128,99 QueryKind = ValueQuery,100 >;101}102103pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);104impl<T: Config> FungibleHandle<T> {105 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {106 Self(inner)107 }108 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {109 self.0110 }111}112impl<T: Config> WithRecorder<T> for FungibleHandle<T> {113 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {114 self.0.recorder()115 }116 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {117 self.0.into_recorder()118 }119}120impl<T: Config> Deref for FungibleHandle<T> {121 type Target = pallet_common::CollectionHandle<T>;122123 fn deref(&self) -> &Self::Target {124 &self.0125 }126}127128impl<T: Config> Pallet<T> {129 pub fn init_collection(130 owner: T::AccountId,131 data: CreateCollectionData<T::AccountId>,132 ) -> Result<CollectionId, DispatchError> {133 <PalletCommon<T>>::init_collection(owner, data)134 }135 pub fn destroy_collection(136 collection: FungibleHandle<T>,137 sender: &T::CrossAccountId,138 ) -> DispatchResult {139 let id = collection.id;140141 142143 PalletCommon::destroy_collection(collection.0, sender)?;144145 <TotalSupply<T>>::remove(id);146 <Balance<T>>::remove_prefix((id,), None);147 <Allowance<T>>::remove_prefix((id,), None);148 Ok(())149 }150151 pub fn burn(152 collection: &FungibleHandle<T>,153 owner: &T::CrossAccountId,154 amount: u128,155 ) -> DispatchResult {156 let total_supply = <TotalSupply<T>>::get(collection.id)157 .checked_sub(amount)158 .ok_or(<CommonError<T>>::TokenValueTooLow)?;159160 let balance = <Balance<T>>::get((collection.id, owner))161 .checked_sub(amount)162 .ok_or(<CommonError<T>>::TokenValueTooLow)?;163164 if collection.access == AccessMode::AllowList {165 collection.check_allowlist(owner)?;166 }167168 169170 if balance == 0 {171 <Balance<T>>::remove((collection.id, owner));172 } else {173 <Balance<T>>::insert((collection.id, owner), balance);174 }175 <TotalSupply<T>>::insert(collection.id, total_supply);176177 collection.log_mirrored(ERC20Events::Transfer {178 from: *owner.as_eth(),179 to: H160::default(),180 value: amount.into(),181 });182 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(183 collection.id,184 TokenId::default(),185 owner.clone(),186 amount,187 ));188 Ok(())189 }190191 pub fn transfer(192 collection: &FungibleHandle<T>,193 from: &T::CrossAccountId,194 to: &T::CrossAccountId,195 amount: u128,196 nesting_budget: &dyn Budget,197 ) -> DispatchResult {198 ensure!(199 collection.limits.transfers_enabled(),200 <CommonError<T>>::TransferNotAllowed,201 );202203 if collection.access == AccessMode::AllowList {204 collection.check_allowlist(from)?;205 collection.check_allowlist(to)?;206 }207 <PalletCommon<T>>::ensure_correct_receiver(to)?;208209 let balance_from = <Balance<T>>::get((collection.id, from))210 .checked_sub(amount)211 .ok_or(<CommonError<T>>::TokenValueTooLow)?;212 let balance_to = if from != to {213 Some(214 <Balance<T>>::get((collection.id, to))215 .checked_add(amount)216 .ok_or(ArithmeticError::Overflow)?,217 )218 } else {219 None220 };221222 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {223 let handle = <CollectionHandle<T>>::try_get(target.0)?;224 let dispatch = T::CollectionDispatch::dispatch(handle);225 let dispatch = dispatch.as_dyn();226227 dispatch.check_nesting(228 from.clone(),229 (collection.id, TokenId::default()),230 target.1,231 nesting_budget,232 )?;233 }234235 236237 if let Some(balance_to) = balance_to {238 239 if balance_from == 0 {240 <Balance<T>>::remove((collection.id, from));241 } else {242 <Balance<T>>::insert((collection.id, from), balance_from);243 }244 <Balance<T>>::insert((collection.id, to), balance_to);245 }246247 collection.log_mirrored(ERC20Events::Transfer {248 from: *from.as_eth(),249 to: *to.as_eth(),250 value: amount.into(),251 });252 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(253 collection.id,254 TokenId::default(),255 from.clone(),256 to.clone(),257 amount,258 ));259 Ok(())260 }261262 pub fn create_multiple_items(263 collection: &FungibleHandle<T>,264 sender: &T::CrossAccountId,265 data: BTreeMap<T::CrossAccountId, u128>,266 nesting_budget: &dyn Budget,267 ) -> DispatchResult {268 if !collection.is_owner_or_admin(sender) {269 ensure!(270 collection.mint_mode,271 <CommonError<T>>::PublicMintingNotAllowed272 );273 collection.check_allowlist(sender)?;274275 for (owner, _) in data.iter() {276 collection.check_allowlist(owner)?;277 }278 }279280 let total_supply = data281 .iter()282 .map(|(_, v)| *v)283 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {284 acc.checked_add(v)285 })286 .ok_or(ArithmeticError::Overflow)?;287288 let mut balances = data;289 for (k, v) in balances.iter_mut() {290 *v = <Balance<T>>::get((collection.id, &k))291 .checked_add(*v)292 .ok_or(ArithmeticError::Overflow)?;293 }294295 for (to, _) in balances.iter() {296 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {297 let handle = <CollectionHandle<T>>::try_get(target.0)?;298 let dispatch = T::CollectionDispatch::dispatch(handle);299 let dispatch = dispatch.as_dyn();300301 dispatch.check_nesting(302 sender.clone(),303 (collection.id, TokenId::default()),304 target.1,305 nesting_budget,306 )?;307 }308 }309310 311312 <TotalSupply<T>>::insert(collection.id, total_supply);313 for (user, amount) in balances {314 <Balance<T>>::insert((collection.id, &user), amount);315316 collection.log_mirrored(ERC20Events::Transfer {317 from: H160::default(),318 to: *user.as_eth(),319 value: amount.into(),320 });321 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(322 collection.id,323 TokenId::default(),324 user.clone(),325 amount,326 ));327 }328329 Ok(())330 }331332 fn set_allowance_unchecked(333 collection: &FungibleHandle<T>,334 owner: &T::CrossAccountId,335 spender: &T::CrossAccountId,336 amount: u128,337 ) {338 if amount == 0 {339 <Allowance<T>>::remove((collection.id, owner, spender));340 } else {341 <Allowance<T>>::insert((collection.id, owner, spender), amount);342 }343344 collection.log_mirrored(ERC20Events::Approval {345 owner: *owner.as_eth(),346 spender: *spender.as_eth(),347 value: amount.into(),348 });349 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(350 collection.id,351 TokenId(0),352 owner.clone(),353 spender.clone(),354 amount,355 ));356 }357358 pub fn set_allowance(359 collection: &FungibleHandle<T>,360 owner: &T::CrossAccountId,361 spender: &T::CrossAccountId,362 amount: u128,363 ) -> DispatchResult {364 if collection.access == AccessMode::AllowList {365 collection.check_allowlist(owner)?;366 collection.check_allowlist(spender)?;367 }368369 if <Balance<T>>::get((collection.id, owner)) < amount {370 ensure!(371 collection.ignores_owned_amount(owner),372 <CommonError<T>>::CantApproveMoreThanOwned373 );374 }375376 377378 Self::set_allowance_unchecked(collection, owner, spender, amount);379 Ok(())380 }381382 fn check_allowed(383 collection: &FungibleHandle<T>,384 spender: &T::CrossAccountId,385 from: &T::CrossAccountId,386 amount: u128,387 nesting_budget: &dyn Budget,388 ) -> Result<Option<u128>, DispatchError> {389 if spender.conv_eq(from) {390 return Ok(None);391 }392 if collection.access == AccessMode::AllowList {393 394 collection.check_allowlist(spender)?;395 }396 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {397 398 ensure!(399 <PalletStructure<T>>::check_indirectly_owned(400 spender.clone(),401 source.0,402 source.1,403 None,404 nesting_budget405 )?,406 <CommonError<T>>::ApprovedValueTooLow,407 );408 return Ok(None);409 }410 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);411 if allowance.is_none() {412 ensure!(413 collection.ignores_allowance(spender),414 <CommonError<T>>::ApprovedValueTooLow415 );416 }417418 Ok(allowance)419 }420421 pub fn transfer_from(422 collection: &FungibleHandle<T>,423 spender: &T::CrossAccountId,424 from: &T::CrossAccountId,425 to: &T::CrossAccountId,426 amount: u128,427 nesting_budget: &dyn Budget,428 ) -> DispatchResult {429 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;430431 432433 Self::transfer(collection, from, to, amount, nesting_budget)?;434 if let Some(allowance) = allowance {435 Self::set_allowance_unchecked(collection, from, spender, allowance);436 }437 Ok(())438 }439440 pub fn burn_from(441 collection: &FungibleHandle<T>,442 spender: &T::CrossAccountId,443 from: &T::CrossAccountId,444 amount: u128,445 nesting_budget: &dyn Budget,446 ) -> DispatchResult {447 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;448449 450451 Self::burn(collection, from, amount)?;452 if let Some(allowance) = allowance {453 Self::set_allowance_unchecked(collection, from, spender, allowance);454 }455 Ok(())456 }457458 459 pub fn create_item(460 collection: &FungibleHandle<T>,461 sender: &T::CrossAccountId,462 data: CreateItemData<T>,463 nesting_budget: &dyn Budget,464 ) -> DispatchResult {465 Self::create_multiple_items(466 collection,467 sender,468 [(data.0, data.1)].into_iter().collect(),469 nesting_budget,470 )471 }472}