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

difftreelog

source

pallets/refungible/src/lib.rs18.5 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#[struct_versioning::versioned(version = 2, upper)]45#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]46pub struct ItemData {47	pub const_data: BoundedVec<u8, CustomDataLimit>,4849	#[version(..2)]50	pub variable_data: BoundedVec<u8, CustomDataLimit>,51}5253#[frame_support::pallet]54pub mod pallet {55	use super::*;56	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};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::AccountId,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		// =========212213		PalletCommon::destroy_collection(collection.0, sender)?;214215		<TokensMinted<T>>::remove(id);216		<TokensBurnt<T>>::remove(id);217		<TokenData<T>>::remove_prefix((id,), None);218		<TotalSupply<T>>::remove_prefix((id,), None);219		<Balance<T>>::remove_prefix((id,), None);220		<Allowance<T>>::remove_prefix((id,), None);221		<Owned<T>>::remove_prefix((id,), None);222		<AccountBalance<T>>::remove_prefix((id,), None);223		Ok(())224	}225226	pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {227		let burnt = <TokensBurnt<T>>::get(collection.id)228			.checked_add(1)229			.ok_or(ArithmeticError::Overflow)?;230231		<TokensBurnt<T>>::insert(collection.id, burnt);232		<TokenData<T>>::remove((collection.id, token_id));233		<TotalSupply<T>>::remove((collection.id, token_id));234		<Balance<T>>::remove_prefix((collection.id, token_id), None);235		<Allowance<T>>::remove_prefix((collection.id, token_id), None);236		// TODO: ERC721 transfer event237		Ok(())238	}239240	pub fn burn(241		collection: &RefungibleHandle<T>,242		owner: &T::CrossAccountId,243		token: TokenId,244		amount: u128,245	) -> DispatchResult {246		let total_supply = <TotalSupply<T>>::get((collection.id, token))247			.checked_sub(amount)248			.ok_or(<CommonError<T>>::TokenValueTooLow)?;249250		// This was probally last owner of this token?251		if total_supply == 0 {252			// Ensure user actually owns this amount253			ensure!(254				<Balance<T>>::get((collection.id, token, owner)) == amount,255				<CommonError<T>>::TokenValueTooLow256			);257			let account_balance = <AccountBalance<T>>::get((collection.id, owner))258				.checked_sub(1)259				// Should not occur260				.ok_or(ArithmeticError::Underflow)?;261262			// =========263264			<Owned<T>>::remove((collection.id, owner, token));265			<AccountBalance<T>>::insert((collection.id, owner), account_balance);266			Self::burn_token(collection, token)?;267			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(268				collection.id,269				token,270				owner.clone(),271				amount,272			));273			return Ok(());274		}275276		let balance = <Balance<T>>::get((collection.id, token, owner))277			.checked_sub(amount)278			.ok_or(<CommonError<T>>::TokenValueTooLow)?;279		let account_balance = if balance == 0 {280			<AccountBalance<T>>::get((collection.id, owner))281				.checked_sub(1)282				// Should not occur283				.ok_or(ArithmeticError::Underflow)?284		} else {285			0286		};287288		// =========289290		if balance == 0 {291			<Owned<T>>::remove((collection.id, owner, token));292			<Balance<T>>::remove((collection.id, token, owner));293			<AccountBalance<T>>::insert((collection.id, owner), account_balance);294		} else {295			<Balance<T>>::insert((collection.id, token, owner), balance);296		}297		<TotalSupply<T>>::insert((collection.id, token), total_supply);298		// TODO: ERC20 transfer event299		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(300			collection.id,301			token,302			owner.clone(),303			amount,304		));305		Ok(())306	}307308	pub fn transfer(309		collection: &RefungibleHandle<T>,310		from: &T::CrossAccountId,311		to: &T::CrossAccountId,312		token: TokenId,313		amount: u128,314		nesting_budget: &dyn Budget,315	) -> DispatchResult {316		ensure!(317			collection.limits.transfers_enabled(),318			<CommonError<T>>::TransferNotAllowed319		);320321		if collection.access == AccessMode::AllowList {322			collection.check_allowlist(from)?;323			collection.check_allowlist(to)?;324		}325		<PalletCommon<T>>::ensure_correct_receiver(to)?;326327		let balance_from = <Balance<T>>::get((collection.id, token, from))328			.checked_sub(amount)329			.ok_or(<CommonError<T>>::TokenValueTooLow)?;330		let mut create_target = false;331		let from_to_differ = from != to;332		let balance_to = if from != to {333			let old_balance = <Balance<T>>::get((collection.id, token, to));334			if old_balance == 0 {335				create_target = true;336			}337			Some(338				old_balance339					.checked_add(amount)340					.ok_or(ArithmeticError::Overflow)?,341			)342		} else {343			None344		};345346		let account_balance_from = if balance_from == 0 {347			Some(348				<AccountBalance<T>>::get((collection.id, from))349					.checked_sub(1)350					// Should not occur351					.ok_or(ArithmeticError::Underflow)?,352			)353		} else {354			None355		};356		// Account data is created in token, AccountBalance should be increased357		// But only if from != to as we shouldn't check overflow in this case358		let account_balance_to = if create_target && from_to_differ {359			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))360				.checked_add(1)361				.ok_or(ArithmeticError::Overflow)?;362			ensure!(363				account_balance_to < collection.limits.account_token_ownership_limit(),364				<CommonError<T>>::AccountTokenLimitExceeded,365			);366367			Some(account_balance_to)368		} else {369			None370		};371372		if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {373			let handle = <CollectionHandle<T>>::try_get(target.0)?;374			let dispatch = T::CollectionDispatch::dispatch(handle);375			let dispatch = dispatch.as_dyn();376377			dispatch.check_nesting(378				from.clone(),379				(collection.id, token),380				target.1,381				nesting_budget,382			)?;383		}384385		// =========386387		if let Some(balance_to) = balance_to {388			// from != to389			if balance_from == 0 {390				<Balance<T>>::remove((collection.id, token, from));391			} else {392				<Balance<T>>::insert((collection.id, token, from), balance_from);393			}394			<Balance<T>>::insert((collection.id, token, to), balance_to);395			if let Some(account_balance_from) = account_balance_from {396				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);397				<Owned<T>>::remove((collection.id, from, token));398			}399			if let Some(account_balance_to) = account_balance_to {400				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);401				<Owned<T>>::insert((collection.id, to, token), true);402			}403		}404405		// TODO: ERC20 transfer event406		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(407			collection.id,408			token,409			from.clone(),410			to.clone(),411			amount,412		));413		Ok(())414	}415416	pub fn create_multiple_items(417		collection: &RefungibleHandle<T>,418		sender: &T::CrossAccountId,419		data: Vec<CreateRefungibleExData<T::CrossAccountId>>,420		nesting_budget: &dyn Budget,421	) -> DispatchResult {422		if !collection.is_owner_or_admin(sender) {423			ensure!(424				collection.mint_mode,425				<CommonError<T>>::PublicMintingNotAllowed426			);427			collection.check_allowlist(sender)?;428429			for item in data.iter() {430				for user in item.users.keys() {431					collection.check_allowlist(user)?;432				}433			}434		}435436		for item in data.iter() {437			for (owner, _) in item.users.iter() {438				<PalletCommon<T>>::ensure_correct_receiver(owner)?;439			}440		}441442		// Total pieces per tokens443		let totals = data444			.iter()445			.map(|data| {446				Ok(data447					.users448					.iter()449					.map(|u| u.1)450					.try_fold(0u128, |acc, v| acc.checked_add(*v))451					.ok_or(ArithmeticError::Overflow)?)452			})453			.collect::<Result<Vec<_>, DispatchError>>()?;454		for total in &totals {455			ensure!(456				*total <= MAX_REFUNGIBLE_PIECES,457				<Error<T>>::WrongRefungiblePieces458			);459		}460461		let first_token_id = <TokensMinted<T>>::get(collection.id);462		let tokens_minted = first_token_id463			.checked_add(data.len() as u32)464			.ok_or(ArithmeticError::Overflow)?;465		ensure!(466			tokens_minted < collection.limits.token_limit(),467			<CommonError<T>>::CollectionTokenLimitExceeded468		);469470		let mut balances = BTreeMap::new();471		for data in &data {472			for owner in data.users.keys() {473				let balance = balances474					.entry(owner)475					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));476				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;477478				ensure!(479					*balance <= collection.limits.account_token_ownership_limit(),480					<CommonError<T>>::AccountTokenLimitExceeded,481				);482			}483		}484485		for (i, token) in data.iter().enumerate() {486			let token_id = TokenId(first_token_id + i as u32 + 1);487			for (to, _) in token.users.iter() {488				if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {489					let handle = <CollectionHandle<T>>::try_get(target.0)?;490					let dispatch = T::CollectionDispatch::dispatch(handle);491					let dispatch = dispatch.as_dyn();492493					dispatch.check_nesting(494						sender.clone(),495						(collection.id, token_id),496						target.1,497						nesting_budget,498					)?;499				}500			}501		}502503		// =========504505		<TokensMinted<T>>::insert(collection.id, tokens_minted);506		for (account, balance) in balances {507			<AccountBalance<T>>::insert((collection.id, account), balance);508		}509		for (i, token) in data.into_iter().enumerate() {510			let token_id = first_token_id + i as u32 + 1;511			<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);512513			<TokenData<T>>::insert(514				(collection.id, token_id),515				ItemData {516					const_data: token.const_data,517				},518			);519			for (user, amount) in token.users.into_iter() {520				if amount == 0 {521					continue;522				}523				<Balance<T>>::insert((collection.id, token_id, &user), amount);524				<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);525				// TODO: ERC20 transfer event526				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(527					collection.id,528					TokenId(token_id),529					user,530					amount,531				));532			}533		}534		Ok(())535	}536537	pub fn set_allowance_unchecked(538		collection: &RefungibleHandle<T>,539		sender: &T::CrossAccountId,540		spender: &T::CrossAccountId,541		token: TokenId,542		amount: u128,543	) {544		if amount == 0 {545			<Allowance<T>>::remove((collection.id, token, sender, spender));546		} else {547			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);548		}549		// TODO: ERC20 approval event550		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(551			collection.id,552			token,553			sender.clone(),554			spender.clone(),555			amount,556		))557	}558559	pub fn set_allowance(560		collection: &RefungibleHandle<T>,561		sender: &T::CrossAccountId,562		spender: &T::CrossAccountId,563		token: TokenId,564		amount: u128,565	) -> DispatchResult {566		if collection.access == AccessMode::AllowList {567			collection.check_allowlist(sender)?;568			collection.check_allowlist(spender)?;569		}570571		<PalletCommon<T>>::ensure_correct_receiver(spender)?;572573		if <Balance<T>>::get((collection.id, token, sender)) < amount {574			ensure!(575				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),576				<CommonError<T>>::CantApproveMoreThanOwned577			);578		}579580		// =========581582		Self::set_allowance_unchecked(collection, sender, spender, token, amount);583		Ok(())584	}585586	/// Returns allowance, which should be set after transaction587	fn check_allowed(588		collection: &RefungibleHandle<T>,589		spender: &T::CrossAccountId,590		from: &T::CrossAccountId,591		token: TokenId,592		amount: u128,593		nesting_budget: &dyn Budget,594	) -> Result<Option<u128>, DispatchError> {595		if spender.conv_eq(from) {596			return Ok(None);597		}598		if collection.access == AccessMode::AllowList {599			// `from`, `to` checked in [`transfer`]600			collection.check_allowlist(spender)?;601		}602		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {603			// TODO: should collection owner be allowed to perform this transfer?604			ensure!(605				<PalletStructure<T>>::check_indirectly_owned(606					spender.clone(),607					source.0,608					source.1,609					None,610					nesting_budget611				)?,612				<CommonError<T>>::ApprovedValueTooLow,613			);614			return Ok(None);615		}616		let allowance =617			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);618		if allowance.is_none() {619			ensure!(620				collection.ignores_allowance(spender),621				<CommonError<T>>::ApprovedValueTooLow622			);623		}624		Ok(allowance)625	}626627	pub fn transfer_from(628		collection: &RefungibleHandle<T>,629		spender: &T::CrossAccountId,630		from: &T::CrossAccountId,631		to: &T::CrossAccountId,632		token: TokenId,633		amount: u128,634		nesting_budget: &dyn Budget,635	) -> DispatchResult {636		let allowance =637			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;638639		// =========640641		Self::transfer(collection, from, to, token, amount, nesting_budget)?;642		if let Some(allowance) = allowance {643			Self::set_allowance_unchecked(collection, from, spender, token, allowance);644		}645		Ok(())646	}647648	pub fn burn_from(649		collection: &RefungibleHandle<T>,650		spender: &T::CrossAccountId,651		from: &T::CrossAccountId,652		token: TokenId,653		amount: u128,654		nesting_budget: &dyn Budget,655	) -> DispatchResult {656		let allowance =657			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;658659		// =========660661		Self::burn(collection, from, token, amount)?;662		if let Some(allowance) = allowance {663			Self::set_allowance_unchecked(collection, from, spender, token, allowance);664		}665		Ok(())666	}667668	/// Delegated to `create_multiple_items`669	pub fn create_item(670		collection: &RefungibleHandle<T>,671		sender: &T::CrossAccountId,672		data: CreateRefungibleExData<T::CrossAccountId>,673		nesting_budget: &dyn Budget,674	) -> DispatchResult {675		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)676	}677}