git.delta.rocks / unique-network / refs/commits / 6ac8e66dbab7

difftreelog

source

pallets/fungible/src/lib.rs12.0 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, 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		/// 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		/// Setting item properties is not allowed65		SettingPropertiesNotAllowed,66	}6768	#[pallet::config]69	pub trait Config:70		frame_system::Config + pallet_common::Config + pallet_structure::Config71	{72		type WeightInfo: WeightInfo;73	}7475	#[pallet::pallet]76	#[pallet::generate_store(pub(super) trait Store)]77	pub struct Pallet<T>(_);7879	#[pallet::storage]80	pub type TotalSupply<T: Config> =81		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;8283	#[pallet::storage]84	pub type Balance<T: Config> = StorageNMap<85		Key = (86			Key<Twox64Concat, CollectionId>,87			Key<Blake2_128Concat, T::CrossAccountId>,88		),89		Value = u128,90		QueryKind = ValueQuery,91	>;9293	#[pallet::storage]94	pub type Allowance<T: Config> = StorageNMap<95		Key = (96			Key<Twox64Concat, CollectionId>,97			Key<Blake2_128, T::CrossAccountId>,98			Key<Blake2_128Concat, T::CrossAccountId>,99		),100		Value = u128,101		QueryKind = ValueQuery,102	>;103}104105pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);106impl<T: Config> FungibleHandle<T> {107	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {108		Self(inner)109	}110	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {111		self.0112	}113}114impl<T: Config> WithRecorder<T> for FungibleHandle<T> {115	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {116		self.0.recorder()117	}118	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {119		self.0.into_recorder()120	}121}122impl<T: Config> Deref for FungibleHandle<T> {123	type Target = pallet_common::CollectionHandle<T>;124125	fn deref(&self) -> &Self::Target {126		&self.0127	}128}129130impl<T: Config> Pallet<T> {131	pub fn init_collection(132		owner: T::AccountId,133		data: CreateCollectionData<T::AccountId>,134	) -> Result<CollectionId, DispatchError> {135		<PalletCommon<T>>::init_collection(owner, data)136	}137	pub fn destroy_collection(138		collection: FungibleHandle<T>,139		sender: &T::CrossAccountId,140	) -> DispatchResult {141		let id = collection.id;142143		// =========144145		PalletCommon::destroy_collection(collection.0, sender)?;146147		<TotalSupply<T>>::remove(id);148		<Balance<T>>::remove_prefix((id,), None);149		<Allowance<T>>::remove_prefix((id,), None);150		Ok(())151	}152153	pub fn burn(154		collection: &FungibleHandle<T>,155		owner: &T::CrossAccountId,156		amount: u128,157	) -> DispatchResult {158		let total_supply = <TotalSupply<T>>::get(collection.id)159			.checked_sub(amount)160			.ok_or(<CommonError<T>>::TokenValueTooLow)?;161162		let balance = <Balance<T>>::get((collection.id, owner))163			.checked_sub(amount)164			.ok_or(<CommonError<T>>::TokenValueTooLow)?;165166		if collection.access == AccessMode::AllowList {167			collection.check_allowlist(owner)?;168		}169170		// =========171172		if balance == 0 {173			<Balance<T>>::remove((collection.id, owner));174		} else {175			<Balance<T>>::insert((collection.id, owner), balance);176		}177		<TotalSupply<T>>::insert(collection.id, total_supply);178179		collection.log_mirrored(ERC20Events::Transfer {180			from: *owner.as_eth(),181			to: H160::default(),182			value: amount.into(),183		});184		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(185			collection.id,186			TokenId::default(),187			owner.clone(),188			amount,189		));190		Ok(())191	}192193	pub fn transfer(194		collection: &FungibleHandle<T>,195		from: &T::CrossAccountId,196		to: &T::CrossAccountId,197		amount: u128,198		nesting_budget: &dyn Budget,199	) -> DispatchResult {200		ensure!(201			collection.limits.transfers_enabled(),202			<CommonError<T>>::TransferNotAllowed,203		);204205		if collection.access == AccessMode::AllowList {206			collection.check_allowlist(from)?;207			collection.check_allowlist(to)?;208		}209		<PalletCommon<T>>::ensure_correct_receiver(to)?;210211		let balance_from = <Balance<T>>::get((collection.id, from))212			.checked_sub(amount)213			.ok_or(<CommonError<T>>::TokenValueTooLow)?;214		let balance_to = if from != to {215			Some(216				<Balance<T>>::get((collection.id, to))217					.checked_add(amount)218					.ok_or(ArithmeticError::Overflow)?,219			)220		} else {221			None222		};223224		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {225			let handle = <CollectionHandle<T>>::try_get(target.0)?;226			let dispatch = T::CollectionDispatch::dispatch(handle);227			let dispatch = dispatch.as_dyn();228229			dispatch.check_nesting(230				from.clone(),231				(collection.id, TokenId::default()),232				target.1,233				nesting_budget,234			)?;235		}236237		// =========238239		if let Some(balance_to) = balance_to {240			// from != to241			if balance_from == 0 {242				<Balance<T>>::remove((collection.id, from));243			} else {244				<Balance<T>>::insert((collection.id, from), balance_from);245			}246			<Balance<T>>::insert((collection.id, to), balance_to);247		}248249		collection.log_mirrored(ERC20Events::Transfer {250			from: *from.as_eth(),251			to: *to.as_eth(),252			value: amount.into(),253		});254		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(255			collection.id,256			TokenId::default(),257			from.clone(),258			to.clone(),259			amount,260		));261		Ok(())262	}263264	pub fn create_multiple_items(265		collection: &FungibleHandle<T>,266		sender: &T::CrossAccountId,267		data: BTreeMap<T::CrossAccountId, u128>,268		nesting_budget: &dyn Budget,269	) -> DispatchResult {270		if !collection.is_owner_or_admin(sender) {271			ensure!(272				collection.mint_mode,273				<CommonError<T>>::PublicMintingNotAllowed274			);275			collection.check_allowlist(sender)?;276277			for (owner, _) in data.iter() {278				collection.check_allowlist(owner)?;279			}280		}281282		let total_supply = data283			.iter()284			.map(|(_, v)| *v)285			.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {286				acc.checked_add(v)287			})288			.ok_or(ArithmeticError::Overflow)?;289290		let mut balances = data;291		for (k, v) in balances.iter_mut() {292			*v = <Balance<T>>::get((collection.id, &k))293				.checked_add(*v)294				.ok_or(ArithmeticError::Overflow)?;295		}296297		for (to, _) in balances.iter() {298			if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {299				let handle = <CollectionHandle<T>>::try_get(target.0)?;300				let dispatch = T::CollectionDispatch::dispatch(handle);301				let dispatch = dispatch.as_dyn();302303				dispatch.check_nesting(304					sender.clone(),305					(collection.id, TokenId::default()),306					target.1,307					nesting_budget,308				)?;309			}310		}311312		// =========313314		<TotalSupply<T>>::insert(collection.id, total_supply);315		for (user, amount) in balances {316			<Balance<T>>::insert((collection.id, &user), amount);317318			collection.log_mirrored(ERC20Events::Transfer {319				from: H160::default(),320				to: *user.as_eth(),321				value: amount.into(),322			});323			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(324				collection.id,325				TokenId::default(),326				user.clone(),327				amount,328			));329		}330331		Ok(())332	}333334	fn set_allowance_unchecked(335		collection: &FungibleHandle<T>,336		owner: &T::CrossAccountId,337		spender: &T::CrossAccountId,338		amount: u128,339	) {340		if amount == 0 {341			<Allowance<T>>::remove((collection.id, owner, spender));342		} else {343			<Allowance<T>>::insert((collection.id, owner, spender), amount);344		}345346		collection.log_mirrored(ERC20Events::Approval {347			owner: *owner.as_eth(),348			spender: *spender.as_eth(),349			value: amount.into(),350		});351		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(352			collection.id,353			TokenId(0),354			owner.clone(),355			spender.clone(),356			amount,357		));358	}359360	pub fn set_allowance(361		collection: &FungibleHandle<T>,362		owner: &T::CrossAccountId,363		spender: &T::CrossAccountId,364		amount: u128,365	) -> DispatchResult {366		if collection.access == AccessMode::AllowList {367			collection.check_allowlist(owner)?;368			collection.check_allowlist(spender)?;369		}370371		if <Balance<T>>::get((collection.id, owner)) < amount {372			ensure!(373				collection.ignores_owned_amount(owner),374				<CommonError<T>>::CantApproveMoreThanOwned375			);376		}377378		// =========379380		Self::set_allowance_unchecked(collection, owner, spender, amount);381		Ok(())382	}383384	fn check_allowed(385		collection: &FungibleHandle<T>,386		spender: &T::CrossAccountId,387		from: &T::CrossAccountId,388		amount: u128,389		nesting_budget: &dyn Budget,390	) -> Result<Option<u128>, DispatchError> {391		if spender.conv_eq(from) {392			return Ok(None);393		}394		if collection.access == AccessMode::AllowList {395			// `from`, `to` checked in [`transfer`]396			collection.check_allowlist(spender)?;397		}398		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {399			// TODO: should collection owner be allowed to perform this transfer?400			ensure!(401				<PalletStructure<T>>::check_indirectly_owned(402					spender.clone(),403					source.0,404					source.1,405					None,406					nesting_budget407				)?,408				<CommonError<T>>::ApprovedValueTooLow,409			);410			return Ok(None);411		}412		let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);413		if allowance.is_none() {414			ensure!(415				collection.ignores_allowance(spender),416				<CommonError<T>>::ApprovedValueTooLow417			);418		}419420		Ok(allowance)421	}422423	pub fn transfer_from(424		collection: &FungibleHandle<T>,425		spender: &T::CrossAccountId,426		from: &T::CrossAccountId,427		to: &T::CrossAccountId,428		amount: u128,429		nesting_budget: &dyn Budget,430	) -> DispatchResult {431		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;432433		// =========434435		Self::transfer(collection, from, to, amount, nesting_budget)?;436		if let Some(allowance) = allowance {437			Self::set_allowance_unchecked(collection, from, spender, allowance);438		}439		Ok(())440	}441442	pub fn burn_from(443		collection: &FungibleHandle<T>,444		spender: &T::CrossAccountId,445		from: &T::CrossAccountId,446		amount: u128,447		nesting_budget: &dyn Budget,448	) -> DispatchResult {449		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;450451		// =========452453		Self::burn(collection, from, amount)?;454		if let Some(allowance) = allowance {455			Self::set_allowance_unchecked(collection, from, spender, allowance);456		}457		Ok(())458	}459460	/// Delegated to `create_multiple_items`461	pub fn create_item(462		collection: &FungibleHandle<T>,463		sender: &T::CrossAccountId,464		data: CreateItemData<T>,465		nesting_budget: &dyn Budget,466	) -> DispatchResult {467		Self::create_multiple_items(468			collection,469			sender,470			[(data.0, data.1)].into_iter().collect(),471			nesting_budget,472		)473	}474}