git.delta.rocks / unique-network / refs/commits / 9b4da675e61d

difftreelog

source

pallets/fungible/src/lib.rs12.7 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,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;4647/// todo:doc?48pub type CreateItemData<T> = (<T as pallet_evm::account::Config>::CrossAccountId, u128);49pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;5051#[frame_support::pallet]52pub mod pallet {53	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};54	use up_data_structs::CollectionId;55	use super::weights::WeightInfo;5657	#[pallet::error]58	pub enum Error<T> {59		/// Not Fungible item data used to mint in Fungible collection.60		NotFungibleDataUsedToMintFungibleCollectionToken,61		/// Not default id passed as TokenId argument.62		FungibleItemsHaveNoId,63		/// Tried to set data for fungible item.64		FungibleItemsDontHaveData,65		/// Fungible token does not support nesting.66		FungibleDisallowsNesting,67		/// Setting item properties is not allowed.68		SettingPropertiesNotAllowed,69	}7071	#[pallet::config]72	pub trait Config:73		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config74	{75		type WeightInfo: WeightInfo;76	}7778	#[pallet::pallet]79	#[pallet::generate_store(pub(super) trait Store)]80	pub struct Pallet<T>(_);8182	/// Total amount of fungible tokens inside a collection.83	#[pallet::storage]84	pub type TotalSupply<T: Config> =85		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;8687	/// Amount of tokens owned by an account inside a collection.88	#[pallet::storage]89	pub type Balance<T: Config> = StorageNMap<90		Key = (91			Key<Twox64Concat, CollectionId>,92			Key<Blake2_128Concat, T::CrossAccountId>,93		),94		Value = u128,95		QueryKind = ValueQuery,96	>;9798	/// todo:doc99	#[pallet::storage]100	pub type Allowance<T: Config> = StorageNMap<101		Key = (102			Key<Twox64Concat, CollectionId>,103			Key<Blake2_128, T::CrossAccountId>,104			Key<Blake2_128Concat, T::CrossAccountId>,105		),106		Value = u128,107		QueryKind = ValueQuery,108	>;109}110111pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);112impl<T: Config> FungibleHandle<T> {113	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {114		Self(inner)115	}116	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {117		self.0118	}119	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {120		&mut self.0121	}122}123impl<T: Config> WithRecorder<T> for FungibleHandle<T> {124	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {125		self.0.recorder()126	}127	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {128		self.0.into_recorder()129	}130}131impl<T: Config> Deref for FungibleHandle<T> {132	type Target = pallet_common::CollectionHandle<T>;133134	fn deref(&self) -> &Self::Target {135		&self.0136	}137}138139impl<T: Config> Pallet<T> {140	pub fn init_collection(141		owner: T::CrossAccountId,142		data: CreateCollectionData<T::AccountId>,143	) -> Result<CollectionId, DispatchError> {144		<PalletCommon<T>>::init_collection(owner, data, false)145	}146	pub fn destroy_collection(147		collection: FungibleHandle<T>,148		sender: &T::CrossAccountId,149	) -> DispatchResult {150		let id = collection.id;151152		if Self::collection_has_tokens(id) {153			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());154		}155156		// =========157158		PalletCommon::destroy_collection(collection.0, sender)?;159160		<TotalSupply<T>>::remove(id);161		<Balance<T>>::remove_prefix((id,), None);162		<Allowance<T>>::remove_prefix((id,), None);163		Ok(())164	}165166	fn collection_has_tokens(collection_id: CollectionId) -> bool {167		<TotalSupply<T>>::get(collection_id) != 0168	}169170	pub fn burn(171		collection: &FungibleHandle<T>,172		owner: &T::CrossAccountId,173		amount: u128,174	) -> DispatchResult {175		let total_supply = <TotalSupply<T>>::get(collection.id)176			.checked_sub(amount)177			.ok_or(<CommonError<T>>::TokenValueTooLow)?;178179		let balance = <Balance<T>>::get((collection.id, owner))180			.checked_sub(amount)181			.ok_or(<CommonError<T>>::TokenValueTooLow)?;182183		if collection.permissions.access() == AccessMode::AllowList {184			collection.check_allowlist(owner)?;185		}186187		// =========188189		if balance == 0 {190			<Balance<T>>::remove((collection.id, owner));191			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());192		} else {193			<Balance<T>>::insert((collection.id, owner), balance);194		}195		<TotalSupply<T>>::insert(collection.id, total_supply);196197		<PalletEvm<T>>::deposit_log(198			ERC20Events::Transfer {199				from: *owner.as_eth(),200				to: H160::default(),201				value: amount.into(),202			}203			.to_log(collection_id_to_address(collection.id)),204		);205		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(206			collection.id,207			TokenId::default(),208			owner.clone(),209			amount,210		));211		Ok(())212	}213214	pub fn transfer(215		collection: &FungibleHandle<T>,216		from: &T::CrossAccountId,217		to: &T::CrossAccountId,218		amount: u128,219		nesting_budget: &dyn Budget,220	) -> DispatchResult {221		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			// from != to257			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		if !collection.is_owner_or_admin(sender) {291			ensure!(292				collection.permissions.mint_mode(),293				<CommonError<T>>::PublicMintingNotAllowed294			);295			collection.check_allowlist(sender)?;296297			for (owner, _) in data.iter() {298				collection.check_allowlist(owner)?;299			}300		}301302		let total_supply = data303			.iter()304			.map(|(_, v)| *v)305			.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {306				acc.checked_add(v)307			})308			.ok_or(ArithmeticError::Overflow)?;309310		let mut balances = data;311		for (k, v) in balances.iter_mut() {312			*v = <Balance<T>>::get((collection.id, &k))313				.checked_add(*v)314				.ok_or(ArithmeticError::Overflow)?;315		}316317		for (to, _) in balances.iter() {318			<PalletStructure<T>>::check_nesting(319				sender.clone(),320				to,321				collection.id,322				TokenId::default(),323				nesting_budget,324			)?;325		}326327		// =========328329		<TotalSupply<T>>::insert(collection.id, total_supply);330		for (user, amount) in balances {331			<Balance<T>>::insert((collection.id, &user), amount);332			<PalletStructure<T>>::nest_if_sent_to_token_unchecked(333				&user,334				collection.id,335				TokenId::default(),336			);337			<PalletEvm<T>>::deposit_log(338				ERC20Events::Transfer {339					from: H160::default(),340					to: *user.as_eth(),341					value: amount.into(),342				}343				.to_log(collection_id_to_address(collection.id)),344			);345			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(346				collection.id,347				TokenId::default(),348				user.clone(),349				amount,350			));351		}352353		Ok(())354	}355356	fn set_allowance_unchecked(357		collection: &FungibleHandle<T>,358		owner: &T::CrossAccountId,359		spender: &T::CrossAccountId,360		amount: u128,361	) {362		if amount == 0 {363			<Allowance<T>>::remove((collection.id, owner, spender));364		} else {365			<Allowance<T>>::insert((collection.id, owner, spender), amount);366		}367368		<PalletEvm<T>>::deposit_log(369			ERC20Events::Approval {370				owner: *owner.as_eth(),371				spender: *spender.as_eth(),372				value: amount.into(),373			}374			.to_log(collection_id_to_address(collection.id)),375		);376		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(377			collection.id,378			TokenId(0),379			owner.clone(),380			spender.clone(),381			amount,382		));383	}384385	pub fn set_allowance(386		collection: &FungibleHandle<T>,387		owner: &T::CrossAccountId,388		spender: &T::CrossAccountId,389		amount: u128,390	) -> DispatchResult {391		if collection.permissions.access() == AccessMode::AllowList {392			collection.check_allowlist(owner)?;393			collection.check_allowlist(spender)?;394		}395396		if <Balance<T>>::get((collection.id, owner)) < amount {397			ensure!(398				collection.ignores_owned_amount(owner),399				<CommonError<T>>::CantApproveMoreThanOwned400			);401		}402403		// =========404405		Self::set_allowance_unchecked(collection, owner, spender, amount);406		Ok(())407	}408409	fn check_allowed(410		collection: &FungibleHandle<T>,411		spender: &T::CrossAccountId,412		from: &T::CrossAccountId,413		amount: u128,414		nesting_budget: &dyn Budget,415	) -> Result<Option<u128>, DispatchError> {416		if spender.conv_eq(from) {417			return Ok(None);418		}419		if collection.permissions.access() == AccessMode::AllowList {420			// `from`, `to` checked in [`transfer`]421			collection.check_allowlist(spender)?;422		}423		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {424			// TODO: should collection owner be allowed to perform this transfer?425			ensure!(426				<PalletStructure<T>>::check_indirectly_owned(427					spender.clone(),428					source.0,429					source.1,430					None,431					nesting_budget432				)?,433				<CommonError<T>>::ApprovedValueTooLow,434			);435			return Ok(None);436		}437		let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);438		if allowance.is_none() {439			ensure!(440				collection.ignores_allowance(spender),441				<CommonError<T>>::ApprovedValueTooLow442			);443		}444445		Ok(allowance)446	}447448	pub fn transfer_from(449		collection: &FungibleHandle<T>,450		spender: &T::CrossAccountId,451		from: &T::CrossAccountId,452		to: &T::CrossAccountId,453		amount: u128,454		nesting_budget: &dyn Budget,455	) -> DispatchResult {456		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;457458		// =========459460		Self::transfer(collection, from, to, amount, nesting_budget)?;461		if let Some(allowance) = allowance {462			Self::set_allowance_unchecked(collection, from, spender, allowance);463		}464		Ok(())465	}466467	pub fn burn_from(468		collection: &FungibleHandle<T>,469		spender: &T::CrossAccountId,470		from: &T::CrossAccountId,471		amount: u128,472		nesting_budget: &dyn Budget,473	) -> DispatchResult {474		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;475476		// =========477478		Self::burn(collection, from, amount)?;479		if let Some(allowance) = allowance {480			Self::set_allowance_unchecked(collection, from, spender, allowance);481		}482		Ok(())483	}484485	/// Delegated to `create_multiple_items`486	pub fn create_item(487		collection: &FungibleHandle<T>,488		sender: &T::CrossAccountId,489		data: CreateItemData<T>,490		nesting_budget: &dyn Budget,491	) -> DispatchResult {492		Self::create_multiple_items(493			collection,494			sender,495			[(data.0, data.1)].into_iter().collect(),496			nesting_budget,497		)498	}499}