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

difftreelog

source

pallets/refungible/src/lib.rs18.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 frame_support::{ensure, BoundedVec};20use up_data_structs::{21	AccessMode, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,22	CreateCollectionData, CreateRefungibleExData, mapping::TokenAddressMapping, budget::Budget,23};24use pallet_evm::account::CrossAccountId;25use pallet_common::{26	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, CollectionHandle,27	dispatch::CollectionDispatch,28};29use pallet_structure::Pallet as PalletStructure;30use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};31use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};32use core::ops::Deref;33use codec::{Encode, Decode, MaxEncodedLen};34use scale_info::TypeInfo;3536pub use pallet::*;37#[cfg(feature = "runtime-benchmarks")]38pub mod benchmarking;39pub mod common;40pub mod erc;41pub mod weights;42pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4344#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]45pub struct ItemData {46	pub const_data: BoundedVec<u8, CustomDataLimit>,47	pub variable_data: BoundedVec<u8, CustomDataLimit>,48}4950#[frame_support::pallet]51pub mod pallet {52	use super::*;53	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};54	use up_data_structs::{CollectionId, TokenId};55	use super::weights::WeightInfo;5657	#[pallet::error]58	pub enum Error<T> {59		/// Not Refungible item data used to mint in Refungible collection.60		NotRefungibleDataUsedToMintFungibleCollectionToken,61		/// Maximum refungibility exceeded62		WrongRefungiblePieces,63		/// Refungible token can't nest other tokens64		RefungibleDisallowsNesting,65	}6667	#[pallet::config]68	pub trait Config:69		frame_system::Config + pallet_common::Config + pallet_structure::Config70	{71		type WeightInfo: WeightInfo;72	}7374	#[pallet::pallet]75	#[pallet::generate_store(pub(super) trait Store)]76	pub struct Pallet<T>(_);7778	#[pallet::storage]79	pub type TokensMinted<T: Config> =80		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;81	#[pallet::storage]82	pub type TokensBurnt<T: Config> =83		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;8485	#[pallet::storage]86	pub type TokenData<T: Config> = StorageNMap<87		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),88		Value = ItemData,89		QueryKind = ValueQuery,90	>;9192	#[pallet::storage]93	pub type TotalSupply<T: Config> = StorageNMap<94		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),95		Value = u128,96		QueryKind = ValueQuery,97	>;9899	/// Used to enumerate tokens owned by account100	#[pallet::storage]101	pub type Owned<T: Config> = StorageNMap<102		Key = (103			Key<Twox64Concat, CollectionId>,104			Key<Blake2_128Concat, T::CrossAccountId>,105			Key<Twox64Concat, TokenId>,106		),107		Value = bool,108		QueryKind = ValueQuery,109	>;110111	#[pallet::storage]112	pub type AccountBalance<T: Config> = StorageNMap<113		Key = (114			Key<Twox64Concat, CollectionId>,115			// Owner116			Key<Blake2_128Concat, T::CrossAccountId>,117		),118		Value = u32,119		QueryKind = ValueQuery,120	>;121122	#[pallet::storage]123	pub type Balance<T: Config> = StorageNMap<124		Key = (125			Key<Twox64Concat, CollectionId>,126			Key<Twox64Concat, TokenId>,127			// Owner128			Key<Blake2_128Concat, T::CrossAccountId>,129		),130		Value = u128,131		QueryKind = ValueQuery,132	>;133134	#[pallet::storage]135	pub type Allowance<T: Config> = StorageNMap<136		Key = (137			Key<Twox64Concat, CollectionId>,138			Key<Twox64Concat, TokenId>,139			// Owner140			Key<Blake2_128, T::CrossAccountId>,141			// Spender142			Key<Blake2_128Concat, T::CrossAccountId>,143		),144		Value = u128,145		QueryKind = ValueQuery,146	>;147}148149pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);150impl<T: Config> RefungibleHandle<T> {151	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {152		Self(inner)153	}154	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {155		self.0156	}157}158impl<T: Config> Deref for RefungibleHandle<T> {159	type Target = pallet_common::CollectionHandle<T>;160161	fn deref(&self) -> &Self::Target {162		&self.0163	}164}165166impl<T: Config> Pallet<T> {167	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {168		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)169	}170	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {171		<TotalSupply<T>>::contains_key((collection.id, token))172	}173}174175// unchecked calls skips any permission checks176impl<T: Config> Pallet<T> {177	pub fn init_collection(178		owner: T::AccountId,179		data: CreateCollectionData<T::AccountId>,180	) -> Result<CollectionId, DispatchError> {181		<PalletCommon<T>>::init_collection(owner, data)182	}183	pub fn destroy_collection(184		collection: RefungibleHandle<T>,185		sender: &T::CrossAccountId,186	) -> DispatchResult {187		let id = collection.id;188189		// =========190191		PalletCommon::destroy_collection(collection.0, sender)?;192193		<TokensMinted<T>>::remove(id);194		<TokensBurnt<T>>::remove(id);195		<TokenData<T>>::remove_prefix((id,), None);196		<TotalSupply<T>>::remove_prefix((id,), None);197		<Balance<T>>::remove_prefix((id,), None);198		<Allowance<T>>::remove_prefix((id,), None);199		<Owned<T>>::remove_prefix((id,), None);200		<AccountBalance<T>>::remove_prefix((id,), None);201		Ok(())202	}203204	pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {205		let burnt = <TokensBurnt<T>>::get(collection.id)206			.checked_add(1)207			.ok_or(ArithmeticError::Overflow)?;208209		<TokensBurnt<T>>::insert(collection.id, burnt);210		<TokenData<T>>::remove((collection.id, token_id));211		<TotalSupply<T>>::remove((collection.id, token_id));212		<Balance<T>>::remove_prefix((collection.id, token_id), None);213		<Allowance<T>>::remove_prefix((collection.id, token_id), None);214		// TODO: ERC721 transfer event215		Ok(())216	}217218	pub fn burn(219		collection: &RefungibleHandle<T>,220		owner: &T::CrossAccountId,221		token: TokenId,222		amount: u128,223	) -> DispatchResult {224		let total_supply = <TotalSupply<T>>::get((collection.id, token))225			.checked_sub(amount)226			.ok_or(<CommonError<T>>::TokenValueTooLow)?;227228		// This was probally last owner of this token?229		if total_supply == 0 {230			// Ensure user actually owns this amount231			ensure!(232				<Balance<T>>::get((collection.id, token, owner)) == amount,233				<CommonError<T>>::TokenValueTooLow234			);235			let account_balance = <AccountBalance<T>>::get((collection.id, owner))236				.checked_sub(1)237				// Should not occur238				.ok_or(ArithmeticError::Underflow)?;239240			// =========241242			<Owned<T>>::remove((collection.id, owner, token));243			<AccountBalance<T>>::insert((collection.id, owner), account_balance);244			Self::burn_token(collection, token)?;245			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(246				collection.id,247				token,248				owner.clone(),249				amount,250			));251			return Ok(());252		}253254		let balance = <Balance<T>>::get((collection.id, token, owner))255			.checked_sub(amount)256			.ok_or(<CommonError<T>>::TokenValueTooLow)?;257		let account_balance = if balance == 0 {258			<AccountBalance<T>>::get((collection.id, owner))259				.checked_sub(1)260				// Should not occur261				.ok_or(ArithmeticError::Underflow)?262		} else {263			0264		};265266		// =========267268		if balance == 0 {269			<Owned<T>>::remove((collection.id, owner, token));270			<Balance<T>>::remove((collection.id, token, owner));271			<AccountBalance<T>>::insert((collection.id, owner), account_balance);272		} else {273			<Balance<T>>::insert((collection.id, token, owner), balance);274		}275		<TotalSupply<T>>::insert((collection.id, token), total_supply);276		// TODO: ERC20 transfer event277		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(278			collection.id,279			token,280			owner.clone(),281			amount,282		));283		Ok(())284	}285286	pub fn transfer(287		collection: &RefungibleHandle<T>,288		from: &T::CrossAccountId,289		to: &T::CrossAccountId,290		token: TokenId,291		amount: u128,292		nesting_budget: &dyn Budget,293	) -> DispatchResult {294		ensure!(295			collection.limits.transfers_enabled(),296			<CommonError<T>>::TransferNotAllowed297		);298299		if collection.access == AccessMode::AllowList {300			collection.check_allowlist(from)?;301			collection.check_allowlist(to)?;302		}303		<PalletCommon<T>>::ensure_correct_receiver(to)?;304305		let balance_from = <Balance<T>>::get((collection.id, token, from))306			.checked_sub(amount)307			.ok_or(<CommonError<T>>::TokenValueTooLow)?;308		let mut create_target = false;309		let from_to_differ = from != to;310		let balance_to = if from != to {311			let old_balance = <Balance<T>>::get((collection.id, token, to));312			if old_balance == 0 {313				create_target = true;314			}315			Some(316				old_balance317					.checked_add(amount)318					.ok_or(ArithmeticError::Overflow)?,319			)320		} else {321			None322		};323324		let account_balance_from = if balance_from == 0 {325			Some(326				<AccountBalance<T>>::get((collection.id, from))327					.checked_sub(1)328					// Should not occur329					.ok_or(ArithmeticError::Underflow)?,330			)331		} else {332			None333		};334		// Account data is created in token, AccountBalance should be increased335		// But only if from != to as we shouldn't check overflow in this case336		let account_balance_to = if create_target && from_to_differ {337			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))338				.checked_add(1)339				.ok_or(ArithmeticError::Overflow)?;340			ensure!(341				account_balance_to < collection.limits.account_token_ownership_limit(),342				<CommonError<T>>::AccountTokenLimitExceeded,343			);344345			Some(account_balance_to)346		} else {347			None348		};349350		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {351			let handle = <CollectionHandle<T>>::try_get(target.0)?;352			let dispatch = T::CollectionDispatch::dispatch(handle);353			let dispatch = dispatch.as_dyn();354355			dispatch.check_nesting(356				from.clone(),357				(collection.id, token),358				target.1,359				nesting_budget,360			)?;361		}362363		// =========364365		if let Some(balance_to) = balance_to {366			// from != to367			if balance_from == 0 {368				<Balance<T>>::remove((collection.id, token, from));369			} else {370				<Balance<T>>::insert((collection.id, token, from), balance_from);371			}372			<Balance<T>>::insert((collection.id, token, to), balance_to);373			if let Some(account_balance_from) = account_balance_from {374				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);375				<Owned<T>>::remove((collection.id, from, token));376			}377			if let Some(account_balance_to) = account_balance_to {378				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);379				<Owned<T>>::insert((collection.id, to, token), true);380			}381		}382383		// TODO: ERC20 transfer event384		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(385			collection.id,386			token,387			from.clone(),388			to.clone(),389			amount,390		));391		Ok(())392	}393394	pub fn create_multiple_items(395		collection: &RefungibleHandle<T>,396		sender: &T::CrossAccountId,397		data: Vec<CreateRefungibleExData<T::CrossAccountId>>,398		nesting_budget: &dyn Budget,399	) -> DispatchResult {400		if !collection.is_owner_or_admin(sender) {401			ensure!(402				collection.mint_mode,403				<CommonError<T>>::PublicMintingNotAllowed404			);405			collection.check_allowlist(sender)?;406407			for item in data.iter() {408				for user in item.users.keys() {409					collection.check_allowlist(user)?;410				}411			}412		}413414		for item in data.iter() {415			for (owner, _) in item.users.iter() {416				<PalletCommon<T>>::ensure_correct_receiver(owner)?;417			}418		}419420		// Total pieces per tokens421		let totals = data422			.iter()423			.map(|data| {424				Ok(data425					.users426					.iter()427					.map(|u| u.1)428					.try_fold(0u128, |acc, v| acc.checked_add(*v))429					.ok_or(ArithmeticError::Overflow)?)430			})431			.collect::<Result<Vec<_>, DispatchError>>()?;432		for total in &totals {433			ensure!(434				*total <= MAX_REFUNGIBLE_PIECES,435				<Error<T>>::WrongRefungiblePieces436			);437		}438439		let first_token_id = <TokensMinted<T>>::get(collection.id);440		let tokens_minted = first_token_id441			.checked_add(data.len() as u32)442			.ok_or(ArithmeticError::Overflow)?;443		ensure!(444			tokens_minted < collection.limits.token_limit(),445			<CommonError<T>>::CollectionTokenLimitExceeded446		);447448		let mut balances = BTreeMap::new();449		for data in &data {450			for owner in data.users.keys() {451				let balance = balances452					.entry(owner)453					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));454				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;455456				ensure!(457					*balance <= collection.limits.account_token_ownership_limit(),458					<CommonError<T>>::AccountTokenLimitExceeded,459				);460			}461		}462463		for (i, token) in data.iter().enumerate() {464			let token_id = TokenId(first_token_id + i as u32 + 1);465			for (to, _) in token.users.iter() {466				if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {467					let handle = <CollectionHandle<T>>::try_get(target.0)?;468					let dispatch = T::CollectionDispatch::dispatch(handle);469					let dispatch = dispatch.as_dyn();470471					dispatch.check_nesting(472						sender.clone(),473						(collection.id, token_id),474						target.1,475						nesting_budget,476					)?;477				}478			}479		}480481		// =========482483		<TokensMinted<T>>::insert(collection.id, tokens_minted);484		for (account, balance) in balances {485			<AccountBalance<T>>::insert((collection.id, account), balance);486		}487		for (i, token) in data.into_iter().enumerate() {488			let token_id = first_token_id + i as u32 + 1;489			<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);490491			<TokenData<T>>::insert(492				(collection.id, token_id),493				ItemData {494					const_data: token.const_data,495					variable_data: token.variable_data,496				},497			);498			for (user, amount) in token.users.into_iter() {499				if amount == 0 {500					continue;501				}502				<Balance<T>>::insert((collection.id, token_id, &user), amount);503				<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);504				// TODO: ERC20 transfer event505				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(506					collection.id,507					TokenId(token_id),508					user,509					amount,510				));511			}512		}513		Ok(())514	}515516	pub fn set_allowance_unchecked(517		collection: &RefungibleHandle<T>,518		sender: &T::CrossAccountId,519		spender: &T::CrossAccountId,520		token: TokenId,521		amount: u128,522	) {523		if amount == 0 {524			<Allowance<T>>::remove((collection.id, token, sender, spender));525		} else {526			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);527		}528		// TODO: ERC20 approval event529		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(530			collection.id,531			token,532			sender.clone(),533			spender.clone(),534			amount,535		))536	}537538	pub fn set_allowance(539		collection: &RefungibleHandle<T>,540		sender: &T::CrossAccountId,541		spender: &T::CrossAccountId,542		token: TokenId,543		amount: u128,544	) -> DispatchResult {545		if collection.access == AccessMode::AllowList {546			collection.check_allowlist(sender)?;547			collection.check_allowlist(spender)?;548		}549550		<PalletCommon<T>>::ensure_correct_receiver(spender)?;551552		if <Balance<T>>::get((collection.id, token, sender)) < amount {553			ensure!(554				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),555				<CommonError<T>>::CantApproveMoreThanOwned556			);557		}558559		// =========560561		Self::set_allowance_unchecked(collection, sender, spender, token, amount);562		Ok(())563	}564565	/// Returns allowance, which should be set after transaction566	fn check_allowed(567		collection: &RefungibleHandle<T>,568		spender: &T::CrossAccountId,569		from: &T::CrossAccountId,570		token: TokenId,571		amount: u128,572		nesting_budget: &dyn Budget,573	) -> Result<Option<u128>, DispatchError> {574		if spender.conv_eq(from) {575			return Ok(None);576		}577		if collection.access == AccessMode::AllowList {578			// `from`, `to` checked in [`transfer`]579			collection.check_allowlist(spender)?;580		}581		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {582			// TODO: should collection owner be allowed to perform this transfer?583			ensure!(584				<PalletStructure<T>>::check_indirectly_owned(585					spender.clone(),586					source.0,587					source.1,588					None,589					nesting_budget590				)?,591				<CommonError<T>>::ApprovedValueTooLow,592			);593			return Ok(None);594		}595		let allowance =596			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);597		if allowance.is_none() {598			ensure!(599				collection.ignores_allowance(spender),600				<CommonError<T>>::ApprovedValueTooLow601			);602		}603		Ok(allowance)604	}605606	pub fn transfer_from(607		collection: &RefungibleHandle<T>,608		spender: &T::CrossAccountId,609		from: &T::CrossAccountId,610		to: &T::CrossAccountId,611		token: TokenId,612		amount: u128,613		nesting_budget: &dyn Budget,614	) -> DispatchResult {615		let allowance =616			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;617618		// =========619620		Self::transfer(collection, from, to, token, amount, nesting_budget)?;621		if let Some(allowance) = allowance {622			Self::set_allowance_unchecked(collection, from, spender, token, allowance);623		}624		Ok(())625	}626627	pub fn burn_from(628		collection: &RefungibleHandle<T>,629		spender: &T::CrossAccountId,630		from: &T::CrossAccountId,631		token: TokenId,632		amount: u128,633		nesting_budget: &dyn Budget,634	) -> DispatchResult {635		let allowance =636			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;637638		// =========639640		Self::burn(collection, from, token, amount)?;641		if let Some(allowance) = allowance {642			Self::set_allowance_unchecked(collection, from, spender, token, allowance);643		}644		Ok(())645	}646647	pub fn set_variable_metadata(648		collection: &RefungibleHandle<T>,649		sender: &T::CrossAccountId,650		token: TokenId,651		data: BoundedVec<u8, CustomDataLimit>,652	) -> DispatchResult {653		collection.check_can_update_meta(654			sender,655			&T::CrossAccountId::from_sub(collection.owner.clone()),656		)?;657658		let token_data = <TokenData<T>>::get((collection.id, token));659660		// =========661662		<TokenData<T>>::insert(663			(collection.id, token),664			ItemData {665				variable_data: data,666				..token_data667			},668		);669		Ok(())670	}671672	/// Delegated to `create_multiple_items`673	pub fn create_item(674		collection: &RefungibleHandle<T>,675		sender: &T::CrossAccountId,676		data: CreateRefungibleExData<T::CrossAccountId>,677		nesting_budget: &dyn Budget,678	) -> DispatchResult {679		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)680	}681}