git.delta.rocks / unique-network / refs/commits / 55c4d052d75c

difftreelog

source

pallets/fungible/src/lib.rs12.5 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![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, CollectionHandle,29	dispatch::CollectionDispatch, 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		/// Not Fungible item data used to mint in Fungible collection.59		NotFungibleDataUsedToMintFungibleCollectionToken,60		/// Not default id passed as TokenId argument61		FungibleItemsHaveNoId,62		/// Tried to set data for fungible item63		FungibleItemsDontHaveData,64		/// Fungible token does not support nested65		FungibleDisallowsNesting,66		/// Setting item properties is not allowed67		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::AccountId,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		// =========149150		PalletCommon::destroy_collection(collection.0, sender)?;151152		<TotalSupply<T>>::remove(id);153		<Balance<T>>::remove_prefix((id,), None);154		<Allowance<T>>::remove_prefix((id,), None);155		Ok(())156	}157158	pub fn burn(159		collection: &FungibleHandle<T>,160		owner: &T::CrossAccountId,161		amount: u128,162	) -> DispatchResult {163		let total_supply = <TotalSupply<T>>::get(collection.id)164			.checked_sub(amount)165			.ok_or(<CommonError<T>>::TokenValueTooLow)?;166167		let balance = <Balance<T>>::get((collection.id, owner))168			.checked_sub(amount)169			.ok_or(<CommonError<T>>::TokenValueTooLow)?;170171		if collection.access == AccessMode::AllowList {172			collection.check_allowlist(owner)?;173		}174175		// =========176177		if balance == 0 {178			<Balance<T>>::remove((collection.id, owner));179		} else {180			<Balance<T>>::insert((collection.id, owner), balance);181		}182		<TotalSupply<T>>::insert(collection.id, total_supply);183184		<PalletEvm<T>>::deposit_log(185			ERC20Events::Transfer {186				from: *owner.as_eth(),187				to: H160::default(),188				value: amount.into(),189			}190			.to_log(collection_id_to_address(collection.id)),191		);192		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(193			collection.id,194			TokenId::default(),195			owner.clone(),196			amount,197		));198		Ok(())199	}200201	pub fn transfer(202		collection: &FungibleHandle<T>,203		from: &T::CrossAccountId,204		to: &T::CrossAccountId,205		amount: u128,206		nesting_budget: &dyn Budget,207	) -> DispatchResult {208		ensure!(209			collection.limits.transfers_enabled(),210			<CommonError<T>>::TransferNotAllowed,211		);212213		if collection.access == AccessMode::AllowList {214			collection.check_allowlist(from)?;215			collection.check_allowlist(to)?;216		}217		<PalletCommon<T>>::ensure_correct_receiver(to)?;218219		let balance_from = <Balance<T>>::get((collection.id, from))220			.checked_sub(amount)221			.ok_or(<CommonError<T>>::TokenValueTooLow)?;222		let balance_to = if from != to {223			Some(224				<Balance<T>>::get((collection.id, to))225					.checked_add(amount)226					.ok_or(ArithmeticError::Overflow)?,227			)228		} else {229			None230		};231232		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {233			let handle = <CollectionHandle<T>>::try_get(target.0)?;234			let dispatch = T::CollectionDispatch::dispatch(handle);235			let dispatch = dispatch.as_dyn();236237			dispatch.check_nesting(238				from.clone(),239				(collection.id, TokenId::default()),240				target.1,241				nesting_budget,242			)?;243		}244245		// =========246247		if let Some(balance_to) = balance_to {248			// from != to249			if balance_from == 0 {250				<Balance<T>>::remove((collection.id, from));251			} else {252				<Balance<T>>::insert((collection.id, from), balance_from);253			}254			<Balance<T>>::insert((collection.id, to), balance_to);255		}256257		<PalletEvm<T>>::deposit_log(258			ERC20Events::Transfer {259				from: *from.as_eth(),260				to: *to.as_eth(),261				value: amount.into(),262			}263			.to_log(collection_id_to_address(collection.id)),264		);265		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(266			collection.id,267			TokenId::default(),268			from.clone(),269			to.clone(),270			amount,271		));272		Ok(())273	}274275	pub fn create_multiple_items(276		collection: &FungibleHandle<T>,277		sender: &T::CrossAccountId,278		data: BTreeMap<T::CrossAccountId, u128>,279		nesting_budget: &dyn Budget,280	) -> DispatchResult {281		if !collection.is_owner_or_admin(sender) {282			ensure!(283				collection.mint_mode,284				<CommonError<T>>::PublicMintingNotAllowed285			);286			collection.check_allowlist(sender)?;287288			for (owner, _) in data.iter() {289				collection.check_allowlist(owner)?;290			}291		}292293		let total_supply = data294			.iter()295			.map(|(_, v)| *v)296			.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {297				acc.checked_add(v)298			})299			.ok_or(ArithmeticError::Overflow)?;300301		let mut balances = data;302		for (k, v) in balances.iter_mut() {303			*v = <Balance<T>>::get((collection.id, &k))304				.checked_add(*v)305				.ok_or(ArithmeticError::Overflow)?;306		}307308		for (to, _) in balances.iter() {309			if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {310				let handle = <CollectionHandle<T>>::try_get(target.0)?;311				let dispatch = T::CollectionDispatch::dispatch(handle);312				let dispatch = dispatch.as_dyn();313314				dispatch.check_nesting(315					sender.clone(),316					(collection.id, TokenId::default()),317					target.1,318					nesting_budget,319				)?;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);328329			<PalletEvm<T>>::deposit_log(330				ERC20Events::Transfer {331					from: H160::default(),332					to: *user.as_eth(),333					value: amount.into(),334				}335				.to_log(collection_id_to_address(collection.id)),336			);337			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(338				collection.id,339				TokenId::default(),340				user.clone(),341				amount,342			));343		}344345		Ok(())346	}347348	fn set_allowance_unchecked(349		collection: &FungibleHandle<T>,350		owner: &T::CrossAccountId,351		spender: &T::CrossAccountId,352		amount: u128,353	) {354		if amount == 0 {355			<Allowance<T>>::remove((collection.id, owner, spender));356		} else {357			<Allowance<T>>::insert((collection.id, owner, spender), amount);358		}359360		<PalletEvm<T>>::deposit_log(361			ERC20Events::Approval {362				owner: *owner.as_eth(),363				spender: *spender.as_eth(),364				value: amount.into(),365			}366			.to_log(collection_id_to_address(collection.id)),367		);368		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(369			collection.id,370			TokenId(0),371			owner.clone(),372			spender.clone(),373			amount,374		));375	}376377	pub fn set_allowance(378		collection: &FungibleHandle<T>,379		owner: &T::CrossAccountId,380		spender: &T::CrossAccountId,381		amount: u128,382	) -> DispatchResult {383		if collection.access == AccessMode::AllowList {384			collection.check_allowlist(owner)?;385			collection.check_allowlist(spender)?;386		}387388		if <Balance<T>>::get((collection.id, owner)) < amount {389			ensure!(390				collection.ignores_owned_amount(owner),391				<CommonError<T>>::CantApproveMoreThanOwned392			);393		}394395		// =========396397		Self::set_allowance_unchecked(collection, owner, spender, amount);398		Ok(())399	}400401	fn check_allowed(402		collection: &FungibleHandle<T>,403		spender: &T::CrossAccountId,404		from: &T::CrossAccountId,405		amount: u128,406		nesting_budget: &dyn Budget,407	) -> Result<Option<u128>, DispatchError> {408		if spender.conv_eq(from) {409			return Ok(None);410		}411		if collection.access == AccessMode::AllowList {412			// `from`, `to` checked in [`transfer`]413			collection.check_allowlist(spender)?;414		}415		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {416			// TODO: should collection owner be allowed to perform this transfer?417			ensure!(418				<PalletStructure<T>>::check_indirectly_owned(419					spender.clone(),420					source.0,421					source.1,422					None,423					nesting_budget424				)?,425				<CommonError<T>>::ApprovedValueTooLow,426			);427			return Ok(None);428		}429		let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);430		if allowance.is_none() {431			ensure!(432				collection.ignores_allowance(spender),433				<CommonError<T>>::ApprovedValueTooLow434			);435		}436437		Ok(allowance)438	}439440	pub fn transfer_from(441		collection: &FungibleHandle<T>,442		spender: &T::CrossAccountId,443		from: &T::CrossAccountId,444		to: &T::CrossAccountId,445		amount: u128,446		nesting_budget: &dyn Budget,447	) -> DispatchResult {448		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;449450		// =========451452		Self::transfer(collection, from, to, amount, nesting_budget)?;453		if let Some(allowance) = allowance {454			Self::set_allowance_unchecked(collection, from, spender, allowance);455		}456		Ok(())457	}458459	pub fn burn_from(460		collection: &FungibleHandle<T>,461		spender: &T::CrossAccountId,462		from: &T::CrossAccountId,463		amount: u128,464		nesting_budget: &dyn Budget,465	) -> DispatchResult {466		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;467468		// =========469470		Self::burn(collection, from, amount)?;471		if let Some(allowance) = allowance {472			Self::set_allowance_unchecked(collection, from, spender, allowance);473		}474		Ok(())475	}476477	/// Delegated to `create_multiple_items`478	pub fn create_item(479		collection: &FungibleHandle<T>,480		sender: &T::CrossAccountId,481		data: CreateItemData<T>,482		nesting_budget: &dyn Budget,483	) -> DispatchResult {484		Self::create_multiple_items(485			collection,486			sender,487			[(data.0, data.1)].into_iter().collect(),488			nesting_budget,489		)490	}491}