git.delta.rocks / unique-network / refs/commits / 0fa7bd45c6ff

difftreelog

source

pallets/fungible/src/lib.rs9.8 KiBsourcehistory
1#![cfg_attr(not(feature = "std"), no_std)]23use core::ops::Deref;4use frame_support::{ensure};5use up_data_structs::{AccessMode, Collection, CollectionId, TokenId};6use pallet_common::{7	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,8};9use sp_core::H160;10use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};11use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};1213pub use pallet::*;1415use crate::erc::ERC20Events;16#[cfg(feature = "runtime-benchmarks")]17pub mod benchmarking;18pub mod common;19pub mod erc;20pub mod weights;2122pub type CreateItemData<T> = (<T as pallet_common::Config>::CrossAccountId, u128);23pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2425#[frame_support::pallet]26pub mod pallet {27	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};28	use up_data_structs::CollectionId;29	use super::weights::WeightInfo;3031	#[pallet::error]32	pub enum Error<T> {33		/// Not Fungible item data used to mint in Fungible collection.34		NotFungibleDataUsedToMintFungibleCollectionToken,35		/// Not default id passed as TokenId argument36		FungibleItemsHaveNoId,37		/// Tried to set data for fungible item38		FungibleItemsDontHaveData,39	}4041	#[pallet::config]42	pub trait Config: frame_system::Config + pallet_common::Config {43		type WeightInfo: WeightInfo;44	}4546	#[pallet::pallet]47	#[pallet::generate_store(pub(super) trait Store)]48	pub struct Pallet<T>(_);4950	#[pallet::storage]51	pub type TotalSupply<T: Config> =52		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;5354	#[pallet::storage]55	pub type Balance<T: Config> = StorageNMap<56		Key = (57			Key<Twox64Concat, CollectionId>,58			Key<Blake2_128Concat, T::CrossAccountId>,59		),60		Value = u128,61		QueryKind = ValueQuery,62	>;6364	#[pallet::storage]65	pub type Allowance<T: Config> = StorageNMap<66		Key = (67			Key<Twox64Concat, CollectionId>,68			Key<Blake2_128, T::CrossAccountId>,69			Key<Blake2_128Concat, T::CrossAccountId>,70		),71		Value = u128,72		QueryKind = ValueQuery,73	>;74}7576pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);77impl<T: Config> FungibleHandle<T> {78	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {79		Self(inner)80	}81	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {82		self.083	}84}85impl<T: Config> Deref for FungibleHandle<T> {86	type Target = pallet_common::CollectionHandle<T>;8788	fn deref(&self) -> &Self::Target {89		&self.090	}91}9293impl<T: Config> Pallet<T> {94	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {95		<PalletCommon<T>>::init_collection(data)96	}97	pub fn destroy_collection(98		collection: FungibleHandle<T>,99		sender: &T::CrossAccountId,100	) -> DispatchResult {101		let id = collection.id;102103		// =========104105		PalletCommon::destroy_collection(collection.0, sender)?;106107		<TotalSupply<T>>::remove(id);108		<Balance<T>>::remove_prefix((id,), None);109		<Allowance<T>>::remove_prefix((id,), None);110		Ok(())111	}112113	pub fn burn(114		collection: &FungibleHandle<T>,115		owner: &T::CrossAccountId,116		amount: u128,117	) -> DispatchResult {118		let total_supply = <TotalSupply<T>>::get(collection.id)119			.checked_sub(amount)120			.ok_or(<CommonError<T>>::TokenValueTooLow)?;121122		let balance = <Balance<T>>::get((collection.id, owner))123			.checked_sub(amount)124			.ok_or(<CommonError<T>>::TokenValueTooLow)?;125126		if collection.access == AccessMode::AllowList {127			collection.check_allowlist(owner)?;128		}129130		// =========131132		if balance == 0 {133			<Balance<T>>::remove((collection.id, owner));134		} else {135			<Balance<T>>::insert((collection.id, owner), balance);136		}137		<TotalSupply<T>>::insert(collection.id, total_supply);138139		collection.log_infallible(ERC20Events::Transfer {140			from: *owner.as_eth(),141			to: H160::default(),142			value: amount.into(),143		});144		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(145			collection.id,146			TokenId::default(),147			owner.clone(),148			amount,149		));150		Ok(())151	}152153	pub fn transfer(154		collection: &FungibleHandle<T>,155		from: &T::CrossAccountId,156		to: &T::CrossAccountId,157		amount: u128,158	) -> DispatchResult {159		ensure!(160			collection.limits.transfers_enabled(),161			<CommonError<T>>::TransferNotAllowed,162		);163164		if collection.access == AccessMode::AllowList {165			collection.check_allowlist(from)?;166			collection.check_allowlist(to)?;167		}168		<PalletCommon<T>>::ensure_correct_receiver(to)?;169170		let balance_from = <Balance<T>>::get((collection.id, from))171			.checked_sub(amount)172			.ok_or(<CommonError<T>>::TokenValueTooLow)?;173		let balance_to = if from != to {174			Some(175				<Balance<T>>::get((collection.id, to))176					.checked_add(amount)177					.ok_or(ArithmeticError::Overflow)?,178			)179		} else {180			None181		};182183		collection.consume_sstore()?;184		collection.consume_sstore()?;185		collection.consume_log(2, 32)?;186		collection.consume_sstore()?;187188		// =========189190		if let Some(balance_to) = balance_to {191			// from != to192			if balance_from == 0 {193				<Balance<T>>::remove((collection.id, from));194			} else {195				<Balance<T>>::insert((collection.id, from), balance_from);196			}197			<Balance<T>>::insert((collection.id, to), balance_to);198		}199200		collection.log_infallible(ERC20Events::Transfer {201			from: *from.as_eth(),202			to: *to.as_eth(),203			value: amount.into(),204		});205		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(206			collection.id,207			TokenId::default(),208			from.clone(),209			to.clone(),210			amount,211		));212		Ok(())213	}214215	pub fn create_multiple_items(216		collection: &FungibleHandle<T>,217		sender: &T::CrossAccountId,218		data: Vec<CreateItemData<T>>,219	) -> DispatchResult {220		let unrestricted_minting = collection.is_owner_or_admin(sender)?;221		if !unrestricted_minting {222			ensure!(223				collection.mint_mode,224				<CommonError<T>>::PublicMintingNotAllowed225			);226			collection.check_allowlist(sender)?;227228			for (owner, _) in data.iter() {229				collection.check_allowlist(owner)?;230			}231		}232233		let mut balances = BTreeMap::new();234235		let total_supply = data236			.iter()237			.map(|u| u.1)238			.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {239				acc.checked_add(v)240			})241			.ok_or(ArithmeticError::Overflow)?;242243		for (user, amount) in data.into_iter() {244			collection.consume_sload()?;245			let balance = balances246				.entry(user.clone())247				.or_insert_with(|| <Balance<T>>::get((collection.id, user)));248			*balance = (*balance)249				.checked_add(amount)250				.ok_or(ArithmeticError::Overflow)?;251		}252253		collection.consume_sstore()?;254		for _ in &balances {255			collection.consume_sstore()?;256			collection.consume_log(2, 32)?;257			collection.consume_sstore()?;258		}259260		// =========261262		<TotalSupply<T>>::insert(collection.id, total_supply);263		for (user, amount) in balances {264			<Balance<T>>::insert((collection.id, &user), amount);265266			collection.log_infallible(ERC20Events::Transfer {267				from: H160::default(),268				to: *user.as_eth(),269				value: amount.into(),270			});271			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(272				collection.id,273				TokenId::default(),274				user.clone(),275				amount,276			));277		}278279		Ok(())280	}281282	fn set_allowance_unchecked(283		collection: &FungibleHandle<T>,284		owner: &T::CrossAccountId,285		spender: &T::CrossAccountId,286		amount: u128,287	) {288		if amount == 0 {289			<Allowance<T>>::remove((collection.id, owner, spender));290		} else {291			<Allowance<T>>::insert((collection.id, owner, spender), amount);292		}293294		collection.log_infallible(ERC20Events::Approval {295			owner: *owner.as_eth(),296			spender: *spender.as_eth(),297			value: amount.into(),298		});299		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(300			collection.id,301			TokenId(0),302			owner.clone(),303			spender.clone(),304			amount,305		));306	}307308	pub fn set_allowance(309		collection: &FungibleHandle<T>,310		owner: &T::CrossAccountId,311		spender: &T::CrossAccountId,312		amount: u128,313	) -> DispatchResult {314		if collection.access == AccessMode::AllowList {315			collection.check_allowlist(&owner)?;316			collection.check_allowlist(&spender)?;317		}318319		if <Balance<T>>::get((collection.id, owner)) < amount {320			ensure!(321				collection.ignores_owned_amount(owner)?,322				<CommonError<T>>::CantApproveMoreThanOwned323			);324		}325326		// =========327328		Self::set_allowance_unchecked(collection, owner, spender, amount);329		Ok(())330	}331332	pub fn transfer_from(333		collection: &FungibleHandle<T>,334		spender: &T::CrossAccountId,335		from: &T::CrossAccountId,336		to: &T::CrossAccountId,337		amount: u128,338	) -> DispatchResult {339		if spender.conv_eq(from) {340			return Self::transfer(collection, from, to, amount);341		}342		if collection.access == AccessMode::AllowList {343			// `from`, `to` checked in [`transfer`]344			collection.check_allowlist(spender)?;345		}346347		let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);348		if allowance.is_none() {349			ensure!(350				collection.ignores_allowance(spender)?,351				<CommonError<T>>::TokenValueNotEnough352			);353		}354355		// =========356357		Self::transfer(collection, from, to, amount)?;358		if let Some(allowance) = allowance {359			Self::set_allowance_unchecked(collection, from, spender, allowance);360		}361		Ok(())362	}363364	pub fn burn_from(365		collection: &FungibleHandle<T>,366		spender: &T::CrossAccountId,367		from: &T::CrossAccountId,368		amount: u128,369	) -> DispatchResult {370		if spender.conv_eq(from) {371			return Self::burn(collection, from, amount);372		}373		if collection.access == AccessMode::AllowList {374			// `from` checked in [`burn`]375			collection.check_allowlist(spender)?;376		}377378		let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);379		if allowance.is_none() {380			ensure!(381				collection.ignores_allowance(spender)?,382				<CommonError<T>>::TokenValueNotEnough383			);384		}385386		// =========387388		Self::burn(collection, from, amount)?;389		if let Some(allowance) = allowance {390			Self::set_allowance_unchecked(collection, from, spender, allowance);391		}392		Ok(())393	}394395	/// Delegated to `create_multiple_items`396	pub fn create_item(397		collection: &FungibleHandle<T>,398		sender: &T::CrossAccountId,399		data: CreateItemData<T>,400	) -> DispatchResult {401		Self::create_multiple_items(collection, sender, vec![data])402	}403}