git.delta.rocks / unique-network / refs/commits / 5847eccaa1a7

difftreelog

source

pallets/refungible/src/lib.rs18.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 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::{Error as CommonError, Event as CommonEvent, Pallet as PalletCommon};26use pallet_structure::Pallet as PalletStructure;27use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};28use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};29use core::ops::Deref;30use codec::{Encode, Decode, MaxEncodedLen};31use scale_info::TypeInfo;3233pub use pallet::*;34#[cfg(feature = "runtime-benchmarks")]35pub mod benchmarking;36pub mod common;37pub mod erc;38pub mod weights;39pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4041#[struct_versioning::versioned(version = 2, upper)]42#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]43pub struct ItemData {44	pub const_data: BoundedVec<u8, CustomDataLimit>,4546	#[version(..2)]47	pub variable_data: BoundedVec<u8, CustomDataLimit>,48}4950#[frame_support::pallet]51pub mod pallet {52	use super::*;53	use frame_support::{54		Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,55		traits::StorageVersion,56	};57	use frame_system::pallet_prelude::*;58	use up_data_structs::{CollectionId, TokenId};59	use super::weights::WeightInfo;6061	#[pallet::error]62	pub enum Error<T> {63		/// Not Refungible item data used to mint in Refungible collection.64		NotRefungibleDataUsedToMintFungibleCollectionToken,65		/// Maximum refungibility exceeded66		WrongRefungiblePieces,67		/// Refungible token can't nest other tokens68		RefungibleDisallowsNesting,69		/// Setting item properties is not allowed70		SettingPropertiesNotAllowed,71	}7273	#[pallet::config]74	pub trait Config:75		frame_system::Config + pallet_common::Config + pallet_structure::Config76	{77		type WeightInfo: WeightInfo;78	}7980	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);8182	#[pallet::pallet]83	#[pallet::storage_version(STORAGE_VERSION)]84	#[pallet::generate_store(pub(super) trait Store)]85	pub struct Pallet<T>(_);8687	#[pallet::storage]88	pub type TokensMinted<T: Config> =89		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;90	#[pallet::storage]91	pub type TokensBurnt<T: Config> =92		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;9394	#[pallet::storage]95	pub type TokenData<T: Config> = StorageNMap<96		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),97		Value = ItemData,98		QueryKind = ValueQuery,99	>;100101	#[pallet::storage]102	pub type TotalSupply<T: Config> = StorageNMap<103		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),104		Value = u128,105		QueryKind = ValueQuery,106	>;107108	/// Used to enumerate tokens owned by account109	#[pallet::storage]110	pub type Owned<T: Config> = StorageNMap<111		Key = (112			Key<Twox64Concat, CollectionId>,113			Key<Blake2_128Concat, T::CrossAccountId>,114			Key<Twox64Concat, TokenId>,115		),116		Value = bool,117		QueryKind = ValueQuery,118	>;119120	#[pallet::storage]121	pub type AccountBalance<T: Config> = StorageNMap<122		Key = (123			Key<Twox64Concat, CollectionId>,124			// Owner125			Key<Blake2_128Concat, T::CrossAccountId>,126		),127		Value = u32,128		QueryKind = ValueQuery,129	>;130131	#[pallet::storage]132	pub type Balance<T: Config> = StorageNMap<133		Key = (134			Key<Twox64Concat, CollectionId>,135			Key<Twox64Concat, TokenId>,136			// Owner137			Key<Blake2_128Concat, T::CrossAccountId>,138		),139		Value = u128,140		QueryKind = ValueQuery,141	>;142143	#[pallet::storage]144	pub type Allowance<T: Config> = StorageNMap<145		Key = (146			Key<Twox64Concat, CollectionId>,147			Key<Twox64Concat, TokenId>,148			// Owner149			Key<Blake2_128, T::CrossAccountId>,150			// Spender151			Key<Blake2_128Concat, T::CrossAccountId>,152		),153		Value = u128,154		QueryKind = ValueQuery,155	>;156157	#[pallet::hooks]158	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {159		fn on_runtime_upgrade() -> Weight {160			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {161				<TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {162					Some(<ItemDataVersion2>::from(v))163				})164			}165166			0167		}168	}169}170171pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);172impl<T: Config> RefungibleHandle<T> {173	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {174		Self(inner)175	}176	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {177		self.0178	}179}180impl<T: Config> Deref for RefungibleHandle<T> {181	type Target = pallet_common::CollectionHandle<T>;182183	fn deref(&self) -> &Self::Target {184		&self.0185	}186}187188impl<T: Config> Pallet<T> {189	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {190		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)191	}192	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {193		<TotalSupply<T>>::contains_key((collection.id, token))194	}195}196197// unchecked calls skips any permission checks198impl<T: Config> Pallet<T> {199	pub fn init_collection(200		owner: T::CrossAccountId,201		data: CreateCollectionData<T::AccountId>,202	) -> Result<CollectionId, DispatchError> {203		<PalletCommon<T>>::init_collection(owner, data)204	}205	pub fn destroy_collection(206		collection: RefungibleHandle<T>,207		sender: &T::CrossAccountId,208	) -> DispatchResult {209		let id = collection.id;210211		if Self::collection_has_tokens(id) {212			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());213		}214215		// =========216217		PalletCommon::destroy_collection(collection.0, sender)?;218219		<TokensMinted<T>>::remove(id);220		<TokensBurnt<T>>::remove(id);221		<TokenData<T>>::remove_prefix((id,), None);222		<TotalSupply<T>>::remove_prefix((id,), None);223		<Balance<T>>::remove_prefix((id,), None);224		<Allowance<T>>::remove_prefix((id,), None);225		<Owned<T>>::remove_prefix((id,), None);226		<AccountBalance<T>>::remove_prefix((id,), None);227		Ok(())228	}229230	fn collection_has_tokens(collection_id: CollectionId) -> bool {231		<TokenData<T>>::iter_prefix((collection_id,))232			.next()233			.is_some()234	}235236	pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {237		collection.check_is_mutable()?;238		let burnt = <TokensBurnt<T>>::get(collection.id)239			.checked_add(1)240			.ok_or(ArithmeticError::Overflow)?;241242		<TokensBurnt<T>>::insert(collection.id, burnt);243		<TokenData<T>>::remove((collection.id, token_id));244		<TotalSupply<T>>::remove((collection.id, token_id));245		<Balance<T>>::remove_prefix((collection.id, token_id), None);246		<Allowance<T>>::remove_prefix((collection.id, token_id), None);247		// TODO: ERC721 transfer event248		Ok(())249	}250251	pub fn burn(252		collection: &RefungibleHandle<T>,253		owner: &T::CrossAccountId,254		token: TokenId,255		amount: u128,256	) -> DispatchResult {257		collection.check_is_mutable()?;258		let total_supply = <TotalSupply<T>>::get((collection.id, token))259			.checked_sub(amount)260			.ok_or(<CommonError<T>>::TokenValueTooLow)?;261262		// This was probally last owner of this token?263		if total_supply == 0 {264			// Ensure user actually owns this amount265			ensure!(266				<Balance<T>>::get((collection.id, token, owner)) == amount,267				<CommonError<T>>::TokenValueTooLow268			);269			let account_balance = <AccountBalance<T>>::get((collection.id, owner))270				.checked_sub(1)271				// Should not occur272				.ok_or(ArithmeticError::Underflow)?;273274			// =========275276			<Owned<T>>::remove((collection.id, owner, token));277			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);278			<AccountBalance<T>>::insert((collection.id, owner), account_balance);279			Self::burn_token(collection, token)?;280			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(281				collection.id,282				token,283				owner.clone(),284				amount,285			));286			return Ok(());287		}288289		let balance = <Balance<T>>::get((collection.id, token, owner))290			.checked_sub(amount)291			.ok_or(<CommonError<T>>::TokenValueTooLow)?;292		let account_balance = if balance == 0 {293			<AccountBalance<T>>::get((collection.id, owner))294				.checked_sub(1)295				// Should not occur296				.ok_or(ArithmeticError::Underflow)?297		} else {298			0299		};300301		// =========302303		if balance == 0 {304			<Owned<T>>::remove((collection.id, owner, token));305			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);306			<Balance<T>>::remove((collection.id, token, owner));307			<AccountBalance<T>>::insert((collection.id, owner), account_balance);308		} else {309			<Balance<T>>::insert((collection.id, token, owner), balance);310		}311		<TotalSupply<T>>::insert((collection.id, token), total_supply);312		// TODO: ERC20 transfer event313		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(314			collection.id,315			token,316			owner.clone(),317			amount,318		));319		Ok(())320	}321322	pub fn transfer(323		collection: &RefungibleHandle<T>,324		from: &T::CrossAccountId,325		to: &T::CrossAccountId,326		token: TokenId,327		amount: u128,328		nesting_budget: &dyn Budget,329	) -> DispatchResult {330		collection.check_is_mutable()?;331		ensure!(332			collection.limits.transfers_enabled(),333			<CommonError<T>>::TransferNotAllowed334		);335336		if collection.permissions.access() == AccessMode::AllowList {337			collection.check_allowlist(from)?;338			collection.check_allowlist(to)?;339		}340		<PalletCommon<T>>::ensure_correct_receiver(to)?;341342		let balance_from = <Balance<T>>::get((collection.id, token, from))343			.checked_sub(amount)344			.ok_or(<CommonError<T>>::TokenValueTooLow)?;345		let mut create_target = false;346		let from_to_differ = from != to;347		let balance_to = if from != to {348			let old_balance = <Balance<T>>::get((collection.id, token, to));349			if old_balance == 0 {350				create_target = true;351			}352			Some(353				old_balance354					.checked_add(amount)355					.ok_or(ArithmeticError::Overflow)?,356			)357		} else {358			None359		};360361		let account_balance_from = if balance_from == 0 {362			Some(363				<AccountBalance<T>>::get((collection.id, from))364					.checked_sub(1)365					// Should not occur366					.ok_or(ArithmeticError::Underflow)?,367			)368		} else {369			None370		};371		// Account data is created in token, AccountBalance should be increased372		// But only if from != to as we shouldn't check overflow in this case373		let account_balance_to = if create_target && from_to_differ {374			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))375				.checked_add(1)376				.ok_or(ArithmeticError::Overflow)?;377			ensure!(378				account_balance_to < collection.limits.account_token_ownership_limit(),379				<CommonError<T>>::AccountTokenLimitExceeded,380			);381382			Some(account_balance_to)383		} else {384			None385		};386387		// =========388389		<PalletStructure<T>>::nest_if_sent_to_token(390			from.clone(),391			to,392			collection.id,393			token,394			nesting_budget,395		)?;396397		if let Some(balance_to) = balance_to {398			// from != to399			if balance_from == 0 {400				<Balance<T>>::remove((collection.id, token, from));401				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);402			} else {403				<Balance<T>>::insert((collection.id, token, from), balance_from);404			}405			<Balance<T>>::insert((collection.id, token, to), balance_to);406			if let Some(account_balance_from) = account_balance_from {407				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);408				<Owned<T>>::remove((collection.id, from, token));409			}410			if let Some(account_balance_to) = account_balance_to {411				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);412				<Owned<T>>::insert((collection.id, to, token), true);413			}414		}415416		// TODO: ERC20 transfer event417		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(418			collection.id,419			token,420			from.clone(),421			to.clone(),422			amount,423		));424		Ok(())425	}426427	pub fn create_multiple_items(428		collection: &RefungibleHandle<T>,429		sender: &T::CrossAccountId,430		data: Vec<CreateRefungibleExData<T::CrossAccountId>>,431		nesting_budget: &dyn Budget,432	) -> DispatchResult {433		if !collection.is_owner_or_admin(sender) {434			ensure!(435				collection.permissions.mint_mode(),436				<CommonError<T>>::PublicMintingNotAllowed437			);438			collection.check_allowlist(sender)?;439440			for item in data.iter() {441				for user in item.users.keys() {442					collection.check_allowlist(user)?;443				}444			}445		}446447		for item in data.iter() {448			for (owner, _) in item.users.iter() {449				<PalletCommon<T>>::ensure_correct_receiver(owner)?;450			}451		}452453		// Total pieces per tokens454		let totals = data455			.iter()456			.map(|data| {457				Ok(data458					.users459					.iter()460					.map(|u| u.1)461					.try_fold(0u128, |acc, v| acc.checked_add(*v))462					.ok_or(ArithmeticError::Overflow)?)463			})464			.collect::<Result<Vec<_>, DispatchError>>()?;465		for total in &totals {466			ensure!(467				*total <= MAX_REFUNGIBLE_PIECES,468				<Error<T>>::WrongRefungiblePieces469			);470		}471472		let first_token_id = <TokensMinted<T>>::get(collection.id);473		let tokens_minted = first_token_id474			.checked_add(data.len() as u32)475			.ok_or(ArithmeticError::Overflow)?;476		ensure!(477			tokens_minted < collection.limits.token_limit(),478			<CommonError<T>>::CollectionTokenLimitExceeded479		);480481		let mut balances = BTreeMap::new();482		for data in &data {483			for owner in data.users.keys() {484				let balance = balances485					.entry(owner)486					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));487				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;488489				ensure!(490					*balance <= collection.limits.account_token_ownership_limit(),491					<CommonError<T>>::AccountTokenLimitExceeded,492				);493			}494		}495496		for (i, token) in data.iter().enumerate() {497			let token_id = TokenId(first_token_id + i as u32 + 1);498			for (to, _) in token.users.iter() {499				<PalletStructure<T>>::check_nesting(500					sender.clone(),501					to,502					collection.id,503					token_id,504					nesting_budget,505				)?;506			}507		}508509		// =========510511		<TokensMinted<T>>::insert(collection.id, tokens_minted);512		for (account, balance) in balances {513			<AccountBalance<T>>::insert((collection.id, account), balance);514		}515		for (i, token) in data.into_iter().enumerate() {516			let token_id = first_token_id + i as u32 + 1;517			<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);518519			<TokenData<T>>::insert(520				(collection.id, token_id),521				ItemData {522					const_data: token.const_data,523				},524			);525526			for (user, amount) in token.users.into_iter() {527				if amount == 0 {528					continue;529				}530				<Balance<T>>::insert((collection.id, token_id, &user), amount);531				<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);532				<PalletStructure<T>>::nest_if_sent_to_token_unchecked(533					&user,534					collection.id,535					TokenId(token_id),536				);537538				// TODO: ERC20 transfer event539				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(540					collection.id,541					TokenId(token_id),542					user,543					amount,544				));545			}546		}547		Ok(())548	}549550	pub fn set_allowance_unchecked(551		collection: &RefungibleHandle<T>,552		sender: &T::CrossAccountId,553		spender: &T::CrossAccountId,554		token: TokenId,555		amount: u128,556	) {557		if amount == 0 {558			<Allowance<T>>::remove((collection.id, token, sender, spender));559		} else {560			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);561		}562		// TODO: ERC20 approval event563		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(564			collection.id,565			token,566			sender.clone(),567			spender.clone(),568			amount,569		))570	}571572	pub fn set_allowance(573		collection: &RefungibleHandle<T>,574		sender: &T::CrossAccountId,575		spender: &T::CrossAccountId,576		token: TokenId,577		amount: u128,578	) -> DispatchResult {579		collection.check_is_mutable()?;580		if collection.permissions.access() == AccessMode::AllowList {581			collection.check_allowlist(sender)?;582			collection.check_allowlist(spender)?;583		}584585		<PalletCommon<T>>::ensure_correct_receiver(spender)?;586587		if <Balance<T>>::get((collection.id, token, sender)) < amount {588			ensure!(589				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),590				<CommonError<T>>::CantApproveMoreThanOwned591			);592		}593594		// =========595596		Self::set_allowance_unchecked(collection, sender, spender, token, amount);597		Ok(())598	}599600	/// Returns allowance, which should be set after transaction601	fn check_allowed(602		collection: &RefungibleHandle<T>,603		spender: &T::CrossAccountId,604		from: &T::CrossAccountId,605		token: TokenId,606		amount: u128,607		nesting_budget: &dyn Budget,608	) -> Result<Option<u128>, DispatchError> {609		if spender.conv_eq(from) {610			return Ok(None);611		}612		if collection.permissions.access() == AccessMode::AllowList {613			// `from`, `to` checked in [`transfer`]614			collection.check_allowlist(spender)?;615		}616		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {617			// TODO: should collection owner be allowed to perform this transfer?618			ensure!(619				<PalletStructure<T>>::check_indirectly_owned(620					spender.clone(),621					source.0,622					source.1,623					None,624					nesting_budget625				)?,626				<CommonError<T>>::ApprovedValueTooLow,627			);628			return Ok(None);629		}630		let allowance =631			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);632		if allowance.is_none() {633			ensure!(634				collection.ignores_allowance(spender),635				<CommonError<T>>::ApprovedValueTooLow636			);637		}638		Ok(allowance)639	}640641	pub fn transfer_from(642		collection: &RefungibleHandle<T>,643		spender: &T::CrossAccountId,644		from: &T::CrossAccountId,645		to: &T::CrossAccountId,646		token: TokenId,647		amount: u128,648		nesting_budget: &dyn Budget,649	) -> DispatchResult {650		let allowance =651			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;652653		// =========654655		Self::transfer(collection, from, to, token, amount, nesting_budget)?;656		if let Some(allowance) = allowance {657			Self::set_allowance_unchecked(collection, from, spender, token, allowance);658		}659		Ok(())660	}661662	pub fn burn_from(663		collection: &RefungibleHandle<T>,664		spender: &T::CrossAccountId,665		from: &T::CrossAccountId,666		token: TokenId,667		amount: u128,668		nesting_budget: &dyn Budget,669	) -> DispatchResult {670		let allowance =671			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;672673		// =========674675		Self::burn(collection, from, token, amount)?;676		if let Some(allowance) = allowance {677			Self::set_allowance_unchecked(collection, from, spender, token, allowance);678		}679		Ok(())680	}681682	/// Delegated to `create_multiple_items`683	pub fn create_item(684		collection: &RefungibleHandle<T>,685		sender: &T::CrossAccountId,686		data: CreateRefungibleExData<T::CrossAccountId>,687		nesting_budget: &dyn Budget,688	) -> DispatchResult {689		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)690	}691}