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

difftreelog

source

pallets/nonfungible/src/lib.rs15.6 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 erc::ERC721Events;20use frame_support::{BoundedVec, ensure};21use up_data_structs::{22	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,23};24use pallet_common::{25	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,26};27use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};28use sp_core::H160;29use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};30use sp_std::{vec::Vec, vec};31use core::ops::Deref;32use sp_std::collections::btree_map::BTreeMap;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;4243pub type CreateItemData<T> = CreateNftExData<<T as pallet_common::Config>::CrossAccountId>;44pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4546#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]47pub struct ItemData<CrossAccountId> {48	pub const_data: BoundedVec<u8, CustomDataLimit>,49	pub variable_data: BoundedVec<u8, CustomDataLimit>,50	pub owner: CrossAccountId,51}5253#[frame_support::pallet]54pub mod pallet {55	use super::*;56	use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};57	use up_data_structs::{CollectionId, TokenId};58	use super::weights::WeightInfo;5960	#[pallet::error]61	pub enum Error<T> {62		/// Not Nonfungible item data used to mint in Nonfungible collection.63		NotNonfungibleDataUsedToMintFungibleCollectionToken,64		/// Used amount > 1 with NFT65		NonfungibleItemsHaveNoAmount,66	}6768	#[pallet::config]69	pub trait Config: frame_system::Config + pallet_common::Config {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 TokensMinted<T: Config> =79		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;80	#[pallet::storage]81	pub type TokensBurnt<T: Config> =82		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;8384	#[pallet::storage]85	pub type TokenData<T: Config> = StorageNMap<86		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),87		Value = ItemData<T::CrossAccountId>,88		QueryKind = OptionQuery,89	>;9091	/// Used to enumerate tokens owned by account92	#[pallet::storage]93	pub type Owned<T: Config> = StorageNMap<94		Key = (95			Key<Twox64Concat, CollectionId>,96			Key<Blake2_128Concat, T::CrossAccountId>,97			Key<Twox64Concat, TokenId>,98		),99		Value = bool,100		QueryKind = ValueQuery,101	>;102103	#[pallet::storage]104	pub type AccountBalance<T: Config> = StorageNMap<105		Key = (106			Key<Twox64Concat, CollectionId>,107			Key<Blake2_128Concat, T::CrossAccountId>,108		),109		Value = u32,110		QueryKind = ValueQuery,111	>;112113	#[pallet::storage]114	pub type Allowance<T: Config> = StorageNMap<115		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),116		Value = T::CrossAccountId,117		QueryKind = OptionQuery,118	>;119}120121pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);122impl<T: Config> NonfungibleHandle<T> {123	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {124		Self(inner)125	}126	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {127		self.0128	}129}130impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {131	fn recorder(&self) -> &SubstrateRecorder<T> {132		self.0.recorder()133	}134	fn into_recorder(self) -> SubstrateRecorder<T> {135		self.0.into_recorder()136	}137}138impl<T: Config> Deref for NonfungibleHandle<T> {139	type Target = pallet_common::CollectionHandle<T>;140141	fn deref(&self) -> &Self::Target {142		&self.0143	}144}145146impl<T: Config> Pallet<T> {147	pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {148		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)149	}150	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {151		<TokenData<T>>::contains_key((collection.id, token))152	}153}154155// unchecked calls skips any permission checks156impl<T: Config> Pallet<T> {157	pub fn init_collection(158		owner: T::AccountId,159		data: CreateCollectionData<T::AccountId>,160	) -> Result<CollectionId, DispatchError> {161		<PalletCommon<T>>::init_collection(owner, data)162	}163	pub fn destroy_collection(164		collection: NonfungibleHandle<T>,165		sender: &T::CrossAccountId,166	) -> DispatchResult {167		let id = collection.id;168169		// =========170171		PalletCommon::destroy_collection(collection.0, sender)?;172173		<TokenData<T>>::remove_prefix((id,), None);174		<Owned<T>>::remove_prefix((id,), None);175		<TokensMinted<T>>::remove(id);176		<TokensBurnt<T>>::remove(id);177		<Allowance<T>>::remove_prefix((id,), None);178		<AccountBalance<T>>::remove_prefix((id,), None);179		Ok(())180	}181182	pub fn burn(183		collection: &NonfungibleHandle<T>,184		sender: &T::CrossAccountId,185		token: TokenId,186	) -> DispatchResult {187		let token_data =188			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;189		ensure!(190			&token_data.owner == sender191				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),192			<CommonError<T>>::NoPermission193		);194195		if collection.access == AccessMode::AllowList {196			collection.check_allowlist(sender)?;197		}198199		let burnt = <TokensBurnt<T>>::get(collection.id)200			.checked_add(1)201			.ok_or(ArithmeticError::Overflow)?;202203		let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))204			.checked_sub(1)205			.ok_or(ArithmeticError::Overflow)?;206207		if balance == 0 {208			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));209		} else {210			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);211		}212		// =========213214		<Owned<T>>::remove((collection.id, &token_data.owner, token));215		<TokensBurnt<T>>::insert(collection.id, burnt);216		<TokenData<T>>::remove((collection.id, token));217		let old_spender = <Allowance<T>>::take((collection.id, token));218219		if let Some(old_spender) = old_spender {220			<PalletCommon<T>>::deposit_event(CommonEvent::Approved(221				collection.id,222				token,223				sender.clone(),224				old_spender,225				0,226			));227		}228229		collection.log_mirrored(ERC721Events::Transfer {230			from: *token_data.owner.as_eth(),231			to: H160::default(),232			token_id: token.into(),233		});234		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(235			collection.id,236			token,237			token_data.owner,238			1,239		));240		Ok(())241	}242243	pub fn transfer(244		collection: &NonfungibleHandle<T>,245		from: &T::CrossAccountId,246		to: &T::CrossAccountId,247		token: TokenId,248	) -> DispatchResult {249		ensure!(250			collection.limits.transfers_enabled(),251			<CommonError<T>>::TransferNotAllowed252		);253254		let token_data =255			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;256		ensure!(257			&token_data.owner == from258				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),259			<CommonError<T>>::NoPermission260		);261262		if collection.access == AccessMode::AllowList {263			collection.check_allowlist(from)?;264			collection.check_allowlist(to)?;265		}266		<PalletCommon<T>>::ensure_correct_receiver(to)?;267268		let balance_from = <AccountBalance<T>>::get((collection.id, from))269			.checked_sub(1)270			.ok_or(<CommonError<T>>::TokenValueTooLow)?;271		let balance_to = if from != to {272			let balance_to = <AccountBalance<T>>::get((collection.id, to))273				.checked_add(1)274				.ok_or(ArithmeticError::Overflow)?;275276			ensure!(277				balance_to < collection.limits.account_token_ownership_limit(),278				<CommonError<T>>::AccountTokenLimitExceeded,279			);280281			Some(balance_to)282		} else {283			None284		};285286		// =========287288		<TokenData<T>>::insert(289			(collection.id, token),290			ItemData {291				owner: to.clone(),292				..token_data293			},294		);295296		if let Some(balance_to) = balance_to {297			// from != to298			if balance_from == 0 {299				<AccountBalance<T>>::remove((collection.id, from));300			} else {301				<AccountBalance<T>>::insert((collection.id, from), balance_from);302			}303			<AccountBalance<T>>::insert((collection.id, to), balance_to);304			<Owned<T>>::remove((collection.id, from, token));305			<Owned<T>>::insert((collection.id, to, token), true);306		}307		Self::set_allowance_unchecked(collection, from, token, None, true);308309		collection.log_mirrored(ERC721Events::Transfer {310			from: *from.as_eth(),311			to: *to.as_eth(),312			token_id: token.into(),313		});314		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(315			collection.id,316			token,317			from.clone(),318			to.clone(),319			1,320		));321		Ok(())322	}323324	pub fn create_multiple_items(325		collection: &NonfungibleHandle<T>,326		sender: &T::CrossAccountId,327		data: Vec<CreateItemData<T>>,328	) -> DispatchResult {329		if !collection.is_owner_or_admin(sender) {330			ensure!(331				collection.mint_mode,332				<CommonError<T>>::PublicMintingNotAllowed333			);334			collection.check_allowlist(sender)?;335336			for item in data.iter() {337				collection.check_allowlist(&item.owner)?;338			}339		}340341		for data in data.iter() {342			<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;343		}344345		let first_token = <TokensMinted<T>>::get(collection.id);346		let tokens_minted = first_token347			.checked_add(data.len() as u32)348			.ok_or(ArithmeticError::Overflow)?;349		ensure!(350			tokens_minted <= collection.limits.token_limit(),351			<CommonError<T>>::CollectionTokenLimitExceeded352		);353354		let mut balances = BTreeMap::new();355		for data in &data {356			let balance = balances357				.entry(&data.owner)358				.or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));359			*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;360361			ensure!(362				*balance <= collection.limits.account_token_ownership_limit(),363				<CommonError<T>>::AccountTokenLimitExceeded,364			);365		}366367		// =========368369		<TokensMinted<T>>::insert(collection.id, tokens_minted);370		for (account, balance) in balances {371			<AccountBalance<T>>::insert((collection.id, account), balance);372		}373		for (i, data) in data.into_iter().enumerate() {374			let token = first_token + i as u32 + 1;375376			<TokenData<T>>::insert(377				(collection.id, token),378				ItemData {379					const_data: data.const_data,380					variable_data: data.variable_data,381					owner: data.owner.clone(),382				},383			);384			<Owned<T>>::insert((collection.id, &data.owner, token), true);385386			collection.log_mirrored(ERC721Events::Transfer {387				from: H160::default(),388				to: *data.owner.as_eth(),389				token_id: token.into(),390			});391			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(392				collection.id,393				TokenId(token),394				data.owner.clone(),395				1,396			));397		}398		Ok(())399	}400401	pub fn set_allowance_unchecked(402		collection: &NonfungibleHandle<T>,403		sender: &T::CrossAccountId,404		token: TokenId,405		spender: Option<&T::CrossAccountId>,406		assume_implicit_eth: bool,407	) {408		if let Some(spender) = spender {409			let old_spender = <Allowance<T>>::get((collection.id, token));410			<Allowance<T>>::insert((collection.id, token), spender);411			// In ERC721 there is only one possible approved user of token, so we set412			// approved user to spender413			collection.log_mirrored(ERC721Events::Approval {414				owner: *sender.as_eth(),415				approved: *spender.as_eth(),416				token_id: token.into(),417			});418			// In Unique chain, any token can have any amount of approved users, so we need to419			// set allowance of old owner to 0, and allowance of new owner to 1420			if old_spender.as_ref() != Some(spender) {421				if let Some(old_owner) = old_spender {422					<PalletCommon<T>>::deposit_event(CommonEvent::Approved(423						collection.id,424						token,425						sender.clone(),426						old_owner,427						0,428					));429				}430				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(431					collection.id,432					token,433					sender.clone(),434					spender.clone(),435					1,436				));437			}438		} else {439			let old_spender = <Allowance<T>>::take((collection.id, token));440			if !assume_implicit_eth {441				// In ERC721 there is only one possible approved user of token, so we set442				// approved user to zero address443				collection.log_mirrored(ERC721Events::Approval {444					owner: *sender.as_eth(),445					approved: H160::default(),446					token_id: token.into(),447				});448			}449			// In Unique chain, any token can have any amount of approved users, so we need to450			// set allowance of old owner to 0451			if let Some(old_spender) = old_spender {452				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(453					collection.id,454					token,455					sender.clone(),456					old_spender,457					0,458				));459			}460		}461	}462463	pub fn set_allowance(464		collection: &NonfungibleHandle<T>,465		sender: &T::CrossAccountId,466		token: TokenId,467		spender: Option<&T::CrossAccountId>,468	) -> DispatchResult {469		if collection.access == AccessMode::AllowList {470			collection.check_allowlist(sender)?;471			if let Some(spender) = spender {472				collection.check_allowlist(spender)?;473			}474		}475476		if let Some(spender) = spender {477			<PalletCommon<T>>::ensure_correct_receiver(spender)?;478		}479		let token_data =480			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;481		if &token_data.owner != sender {482			ensure!(483				collection.ignores_owned_amount(sender),484				<CommonError<T>>::CantApproveMoreThanOwned485			);486		}487488		// =========489490		Self::set_allowance_unchecked(collection, sender, token, spender, false);491		Ok(())492	}493494	pub fn transfer_from(495		collection: &NonfungibleHandle<T>,496		spender: &T::CrossAccountId,497		from: &T::CrossAccountId,498		to: &T::CrossAccountId,499		token: TokenId,500	) -> DispatchResult {501		if spender.conv_eq(from) {502			return Self::transfer(collection, from, to, token);503		}504		if collection.access == AccessMode::AllowList {505			// `from`, `to` checked in [`transfer`]506			collection.check_allowlist(spender)?;507		}508509		if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {510			ensure!(511				collection.ignores_allowance(spender),512				<CommonError<T>>::ApprovedValueTooLow513			);514		}515516		// =========517518		Self::transfer(collection, from, to, token)?;519		// Allowance is reset in [`transfer`]520		Ok(())521	}522523	pub fn burn_from(524		collection: &NonfungibleHandle<T>,525		spender: &T::CrossAccountId,526		from: &T::CrossAccountId,527		token: TokenId,528	) -> DispatchResult {529		if spender.conv_eq(from) {530			return Self::burn(collection, from, token);531		}532		if collection.access == AccessMode::AllowList {533			// `from` checked in [`burn`]534			collection.check_allowlist(spender)?;535		}536537		if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {538			ensure!(539				collection.ignores_allowance(spender),540				<CommonError<T>>::ApprovedValueTooLow541			);542		}543544		// =========545546		Self::burn(collection, from, token)547	}548549	pub fn set_variable_metadata(550		collection: &NonfungibleHandle<T>,551		sender: &T::CrossAccountId,552		token: TokenId,553		data: BoundedVec<u8, CustomDataLimit>,554	) -> DispatchResult {555		let token_data =556			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;557		collection.check_can_update_meta(sender, &token_data.owner)?;558559		// =========560561		<TokenData<T>>::insert(562			(collection.id, token),563			ItemData {564				variable_data: data,565				..token_data566			},567		);568		Ok(())569	}570571	/// Delegated to `create_multiple_items`572	pub fn create_item(573		collection: &NonfungibleHandle<T>,574		sender: &T::CrossAccountId,575		data: CreateItemData<T>,576	) -> DispatchResult {577		Self::create_multiple_items(collection, sender, vec![data])578	}579}