git.delta.rocks / unique-network / refs/commits / b69837dd758f

difftreelog

source

pallets/fungible/src/lib.rs11.4 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 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,28	CollectionHandle, 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		/// Not Fungible item data used to mint in Fungible collection.57		NotFungibleDataUsedToMintFungibleCollectionToken,58		/// Not default id passed as TokenId argument59		FungibleItemsHaveNoId,60		/// Tried to set data for fungible item61		FungibleItemsDontHaveData,62		/// Fungible token does not support nested63		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	) -> DispatchResult {197		ensure!(198			collection.limits.transfers_enabled(),199			<CommonError<T>>::TransferNotAllowed,200		);201202		if collection.access == AccessMode::AllowList {203			collection.check_allowlist(from)?;204			collection.check_allowlist(to)?;205		}206		<PalletCommon<T>>::ensure_correct_receiver(to)?;207208		let balance_from = <Balance<T>>::get((collection.id, from))209			.checked_sub(amount)210			.ok_or(<CommonError<T>>::TokenValueTooLow)?;211		let balance_to = if from != to {212			Some(213				<Balance<T>>::get((collection.id, to))214					.checked_add(amount)215					.ok_or(ArithmeticError::Overflow)?,216			)217		} else {218			None219		};220221		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {222			let handle = <CollectionHandle<T>>::try_get(target.0)?;223			let dispatch = T::CollectionDispatch::dispatch(handle);224			let dispatch = dispatch.as_dyn();225226			// =========227228			dispatch.nest_token(from.clone(), (collection.id, TokenId::default()), target.1)?;229		}230231		if let Some(balance_to) = balance_to {232			// from != to233			if balance_from == 0 {234				<Balance<T>>::remove((collection.id, from));235			} else {236				<Balance<T>>::insert((collection.id, from), balance_from);237			}238			<Balance<T>>::insert((collection.id, to), balance_to);239		}240241		collection.log_mirrored(ERC20Events::Transfer {242			from: *from.as_eth(),243			to: *to.as_eth(),244			value: amount.into(),245		});246		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(247			collection.id,248			TokenId::default(),249			from.clone(),250			to.clone(),251			amount,252		));253		Ok(())254	}255256	pub fn create_multiple_items(257		collection: &FungibleHandle<T>,258		sender: &T::CrossAccountId,259		data: BTreeMap<T::CrossAccountId, u128>,260	) -> DispatchResult {261		if !collection.is_owner_or_admin(sender) {262			ensure!(263				collection.mint_mode,264				<CommonError<T>>::PublicMintingNotAllowed265			);266			collection.check_allowlist(sender)?;267268			for (owner, _) in data.iter() {269				collection.check_allowlist(owner)?;270			}271		}272273		let total_supply = data274			.iter()275			.map(|(_, v)| *v)276			.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {277				acc.checked_add(v)278			})279			.ok_or(ArithmeticError::Overflow)?;280281		let mut balances = data;282		for (k, v) in balances.iter_mut() {283			*v = <Balance<T>>::get((collection.id, &k))284				.checked_add(*v)285				.ok_or(ArithmeticError::Overflow)?;286		}287288		// =========289290		<TotalSupply<T>>::insert(collection.id, total_supply);291		for (user, amount) in balances {292			<Balance<T>>::insert((collection.id, &user), amount);293294			collection.log_mirrored(ERC20Events::Transfer {295				from: H160::default(),296				to: *user.as_eth(),297				value: amount.into(),298			});299			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(300				collection.id,301				TokenId::default(),302				user.clone(),303				amount,304			));305		}306307		Ok(())308	}309310	fn set_allowance_unchecked(311		collection: &FungibleHandle<T>,312		owner: &T::CrossAccountId,313		spender: &T::CrossAccountId,314		amount: u128,315	) {316		if amount == 0 {317			<Allowance<T>>::remove((collection.id, owner, spender));318		} else {319			<Allowance<T>>::insert((collection.id, owner, spender), amount);320		}321322		collection.log_mirrored(ERC20Events::Approval {323			owner: *owner.as_eth(),324			spender: *spender.as_eth(),325			value: amount.into(),326		});327		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(328			collection.id,329			TokenId(0),330			owner.clone(),331			spender.clone(),332			amount,333		));334	}335336	pub fn set_allowance(337		collection: &FungibleHandle<T>,338		owner: &T::CrossAccountId,339		spender: &T::CrossAccountId,340		amount: u128,341	) -> DispatchResult {342		if collection.access == AccessMode::AllowList {343			collection.check_allowlist(owner)?;344			collection.check_allowlist(spender)?;345		}346347		if <Balance<T>>::get((collection.id, owner)) < amount {348			ensure!(349				collection.ignores_owned_amount(owner),350				<CommonError<T>>::CantApproveMoreThanOwned351			);352		}353354		// =========355356		Self::set_allowance_unchecked(collection, owner, spender, amount);357		Ok(())358	}359360	fn check_allowed(361		collection: &FungibleHandle<T>,362		spender: &T::CrossAccountId,363		from: &T::CrossAccountId,364		amount: u128,365		nesting_budget: &dyn Budget,366	) -> Result<Option<u128>, DispatchError> {367		if spender.conv_eq(from) {368			return Ok(None);369		}370		if collection.access == AccessMode::AllowList {371			// `from`, `to` checked in [`transfer`]372			collection.check_allowlist(spender)?;373		}374		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {375			// TODO: should collection owner be allowed to perform this transfer?376			ensure!(377				<PalletStructure<T>>::indirectly_owned(378					spender.clone(),379					source.0,380					source.1,381					nesting_budget382				)?,383				<CommonError<T>>::ApprovedValueTooLow,384			);385			return Ok(None);386		}387		let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);388		if allowance.is_none() {389			ensure!(390				collection.ignores_allowance(spender),391				<CommonError<T>>::ApprovedValueTooLow392			);393		}394395		Ok(allowance)396	}397398	pub fn transfer_from(399		collection: &FungibleHandle<T>,400		spender: &T::CrossAccountId,401		from: &T::CrossAccountId,402		to: &T::CrossAccountId,403		amount: u128,404		nesting_budget: &dyn Budget,405	) -> DispatchResult {406		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;407408		// =========409410		Self::transfer(collection, from, to, amount)?;411		if let Some(allowance) = allowance {412			Self::set_allowance_unchecked(collection, from, spender, allowance);413		}414		Ok(())415	}416417	pub fn burn_from(418		collection: &FungibleHandle<T>,419		spender: &T::CrossAccountId,420		from: &T::CrossAccountId,421		amount: u128,422		nesting_budget: &dyn Budget,423	) -> DispatchResult {424		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;425426		// =========427428		Self::burn(collection, from, amount)?;429		if let Some(allowance) = allowance {430			Self::set_allowance_unchecked(collection, from, spender, allowance);431		}432		Ok(())433	}434435	/// Delegated to `create_multiple_items`436	pub fn create_item(437		collection: &FungibleHandle<T>,438		sender: &T::CrossAccountId,439		data: CreateItemData<T>,440	) -> DispatchResult {441		Self::create_multiple_items(collection, sender, [(data.0, data.1)].into_iter().collect())442	}443}