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

difftreelog

source

pallets/nonfungible/src/lib.rs14.6 KiBsourcehistory
1#![cfg_attr(not(feature = "std"), no_std)]23use erc::ERC721Events;4use frame_support::{BoundedVec, ensure};5use nft_data_structs::{6	AccessMode, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit, TokenId,7};8use pallet_common::{9	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,10};11use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};12use sp_core::H160;13use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};14use sp_std::{vec::Vec, vec};15use core::ops::Deref;16use sp_std::collections::btree_map::BTreeMap;17use codec::{Encode, Decode};18use scale_info::TypeInfo;1920pub use pallet::*;21#[cfg(feature = "runtime-benchmarks")]22pub mod benchmarking;23pub mod common;24pub mod erc;25pub mod weights;2627pub struct CreateItemData<T: Config> {28	pub const_data: BoundedVec<u8, CustomDataLimit>,29	pub variable_data: BoundedVec<u8, CustomDataLimit>,30	pub owner: T::CrossAccountId,31}32pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;3334#[derive(Encode, Decode, TypeInfo)]35pub struct ItemData<T: Config> {36	pub const_data: Vec<u8>,37	pub variable_data: Vec<u8>,38	pub owner: T::CrossAccountId,39}4041#[frame_support::pallet]42pub mod pallet {43	use super::*;44	use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};45	use nft_data_structs::{CollectionId, TokenId};46	use super::weights::WeightInfo;4748	#[pallet::error]49	pub enum Error<T> {50		/// Not Nonfungible item data used to mint in Nonfungible collection.51		NotNonfungibleDataUsedToMintFungibleCollectionToken,52		/// Used amount > 1 with NFT53		NonfungibleItemsHaveNoAmount,54	}5556	#[pallet::config]57	pub trait Config: frame_system::Config + pallet_common::Config {58		type WeightInfo: WeightInfo;59	}6061	#[pallet::pallet]62	#[pallet::generate_store(pub(super) trait Store)]63	pub struct Pallet<T>(_);6465	#[pallet::storage]66	pub(super) type TokensMinted<T: Config> =67		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;68	#[pallet::storage]69	pub(super) type TokensBurnt<T: Config> =70		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;7172	#[pallet::storage]73	pub(super) type TokenData<T: Config> = StorageNMap<74		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),75		Value = ItemData<T>,76		QueryKind = OptionQuery,77	>;7879	/// Used to enumerate tokens owned by account80	#[pallet::storage]81	pub(super) type Owned<T: Config> = StorageNMap<82		Key = (83			Key<Twox64Concat, CollectionId>,84			Key<Blake2_128Concat, T::CrossAccountId>,85			Key<Twox64Concat, TokenId>,86		),87		Value = bool,88		QueryKind = ValueQuery,89	>;9091	#[pallet::storage]92	pub(super) type AccountBalance<T: Config> = StorageNMap<93		Key = (94			Key<Twox64Concat, CollectionId>,95			Key<Blake2_128Concat, T::CrossAccountId>,96		),97		Value = u32,98		QueryKind = ValueQuery,99	>;100101	#[pallet::storage]102	pub(super) type Allowance<T: Config> = StorageNMap<103		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),104		Value = T::CrossAccountId,105		QueryKind = OptionQuery,106	>;107}108109pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);110impl<T: Config> NonfungibleHandle<T> {111	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {112		Self(inner)113	}114	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {115		self.0116	}117}118impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {119	fn recorder(&self) -> &SubstrateRecorder<T> {120		self.0.recorder()121	}122	fn into_recorder(self) -> SubstrateRecorder<T> {123		self.0.into_recorder()124	}125}126impl<T: Config> Deref for NonfungibleHandle<T> {127	type Target = pallet_common::CollectionHandle<T>;128129	fn deref(&self) -> &Self::Target {130		&self.0131	}132}133134impl<T: Config> Pallet<T> {135	pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {136		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)137	}138	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {139		<TokenData<T>>::contains_key((collection.id, token))140	}141}142143// unchecked calls skips any permission checks144impl<T: Config> Pallet<T> {145	pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {146		PalletCommon::init_collection(data)147	}148	pub fn destroy_collection(149		collection: NonfungibleHandle<T>,150		sender: &T::CrossAccountId,151	) -> DispatchResult {152		let id = collection.id;153154		// =========155156		PalletCommon::destroy_collection(collection.0, sender)?;157158		<TokenData<T>>::remove_prefix((id,), None);159		<Owned<T>>::remove_prefix((id,), None);160		<TokensMinted<T>>::remove(id);161		<TokensBurnt<T>>::remove(id);162		<Allowance<T>>::remove_prefix((id,), None);163		<AccountBalance<T>>::remove_prefix((id,), None);164		Ok(())165	}166167	pub fn burn(168		collection: &NonfungibleHandle<T>,169		sender: &T::CrossAccountId,170		token: TokenId,171	) -> DispatchResult {172		let token_data = <TokenData<T>>::get((collection.id, token))173			.ok_or_else(|| <CommonError<T>>::TokenNotFound)?;174		ensure!(175			&token_data.owner == sender176				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),177			<CommonError<T>>::NoPermission178		);179180		if collection.access == AccessMode::AllowList {181			collection.check_allowlist(sender)?;182		}183184		let burnt = <TokensBurnt<T>>::get(collection.id)185			.checked_add(1)186			.ok_or(ArithmeticError::Overflow)?;187188		// =========189190		<Owned<T>>::remove((collection.id, &token_data.owner, token));191		<TokensBurnt<T>>::insert(collection.id, burnt);192		<TokenData<T>>::remove((collection.id, token));193		let old_spender = <Allowance<T>>::take((collection.id, token));194195		if let Some(old_spender) = old_spender {196			<PalletCommon<T>>::deposit_event(CommonEvent::Approved(197				collection.id,198				token,199				sender.clone(),200				old_spender.clone(),201				0,202			));203		}204205		collection.log(ERC721Events::Transfer {206			from: *token_data.owner.as_eth(),207			to: H160::default(),208			token_id: token.into(),209		});210		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(211			collection.id,212			token,213			token_data.owner,214			1,215		));216		return Ok(());217	}218219	pub fn transfer(220		collection: &NonfungibleHandle<T>,221		from: &T::CrossAccountId,222		to: &T::CrossAccountId,223		token: TokenId,224	) -> DispatchResult {225		ensure!(226			collection.limits.transfers_enabled(),227			<CommonError<T>>::TransferNotAllowed228		);229230		let token_data = <TokenData<T>>::get((collection.id, token))231			.ok_or_else(|| <CommonError<T>>::TokenNotFound)?;232		ensure!(233			&token_data.owner == from234				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),235			<CommonError<T>>::NoPermission236		);237238		if collection.access == AccessMode::AllowList {239			collection.check_allowlist(from)?;240			collection.check_allowlist(to)?;241		}242		<PalletCommon<T>>::ensure_correct_receiver(to)?;243244		let balance_from = <AccountBalance<T>>::get((collection.id, from))245			.checked_sub(1)246			.ok_or(<CommonError<T>>::TokenValueTooLow)?;247		let balance_to = if from != to {248			let balance_to = <AccountBalance<T>>::get((collection.id, to))249				.checked_add(1)250				.ok_or(ArithmeticError::Overflow)?;251252			ensure!(253				balance_to < collection.limits.account_token_ownership_limit(),254				<CommonError<T>>::AccountTokenLimitExceeded,255			);256257			Some(balance_to)258		} else {259			None260		};261262		// =========263264		<TokenData<T>>::insert(265			(collection.id, token),266			ItemData {267				owner: to.clone(),268				..token_data269			},270		);271272		if let Some(balance_to) = balance_to {273			// from != to274			if balance_from == 0 {275				<AccountBalance<T>>::remove((collection.id, from));276			} else {277				<AccountBalance<T>>::insert((collection.id, from), balance_from);278			}279			<AccountBalance<T>>::insert((collection.id, to), balance_to);280			<Owned<T>>::remove((collection.id, from, token));281			<Owned<T>>::insert((collection.id, to, token), true);282		}283		Self::set_allowance_unchecked(collection, from, token, None, true);284285		collection.log(ERC721Events::Transfer {286			from: *from.as_eth(),287			to: *to.as_eth(),288			token_id: token.into(),289		});290		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(291			collection.id,292			token,293			from.clone(),294			to.clone(),295			1,296		));297		Ok(())298	}299300	pub fn create_multiple_items(301		collection: &NonfungibleHandle<T>,302		sender: &T::CrossAccountId,303		data: Vec<CreateItemData<T>>,304	) -> DispatchResult {305		if !collection.is_owner_or_admin(sender) {306			ensure!(307				collection.mint_mode,308				<CommonError<T>>::PublicMintingNotAllowed309			);310			collection.check_allowlist(sender)?;311312			for item in data.iter() {313				collection.check_allowlist(&item.owner)?;314			}315		}316317		for data in data.iter() {318			<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;319		}320321		let first_token = <TokensMinted<T>>::get(collection.id);322		let tokens_minted = first_token323			.checked_add(data.len() as u32)324			.ok_or(ArithmeticError::Overflow)?;325		ensure!(326			tokens_minted < collection.limits.token_limit(),327			<CommonError<T>>::CollectionTokenLimitExceeded328		);329330		let mut balances = BTreeMap::new();331		for data in &data {332			let balance = balances333				.entry(&data.owner)334				.or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));335			*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;336337			ensure!(338				*balance <= collection.limits.account_token_ownership_limit(),339				<CommonError<T>>::AccountTokenLimitExceeded,340			);341		}342343		// =========344345		<TokensMinted<T>>::insert(collection.id, tokens_minted);346		for (account, balance) in balances {347			<AccountBalance<T>>::insert((collection.id, account), balance);348		}349		for (i, data) in data.into_iter().enumerate() {350			let token = first_token + i as u32 + 1;351352			<TokenData<T>>::insert(353				(collection.id, token),354				ItemData {355					const_data: data.const_data.into(),356					variable_data: data.variable_data.into(),357					owner: data.owner.clone(),358				},359			);360			<Owned<T>>::insert((collection.id, &data.owner, token), true);361362			collection.log(ERC721Events::Transfer {363				from: H160::default(),364				to: *data.owner.as_eth(),365				token_id: token.into(),366			});367			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(368				collection.id,369				TokenId(token),370				data.owner.clone(),371				1,372			));373		}374		Ok(())375	}376377	pub fn set_allowance_unchecked(378		collection: &NonfungibleHandle<T>,379		sender: &T::CrossAccountId,380		token: TokenId,381		spender: Option<&T::CrossAccountId>,382		assume_implicit_eth: bool,383	) {384		if let Some(spender) = spender {385			let old_spender = <Allowance<T>>::get((collection.id, token));386			<Allowance<T>>::insert((collection.id, token), spender);387			// In ERC721 there is only one possible approved user of token, so we set388			// approved user to spender389			collection.log(ERC721Events::Approval {390				owner: *sender.as_eth(),391				approved: *spender.as_eth(),392				token_id: token.into(),393			});394			// In Unique chain, any token can have any amount of approved users, so we need to395			// set allowance of old owner to 0, and allowance of new owner to 1396			if old_spender.as_ref() != Some(spender) {397				if let Some(old_owner) = old_spender {398					<PalletCommon<T>>::deposit_event(CommonEvent::Approved(399						collection.id,400						token,401						sender.clone(),402						old_owner.clone(),403						0,404					));405				}406				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(407					collection.id,408					token,409					sender.clone(),410					spender.clone(),411					1,412				));413			}414		} else {415			let old_spender = <Allowance<T>>::take((collection.id, token));416			if !assume_implicit_eth {417				// In ERC721 there is only one possible approved user of token, so we set418				// approved user to zero address419				collection.log(ERC721Events::Approval {420					owner: *sender.as_eth(),421					approved: H160::default(),422					token_id: token.into(),423				});424			}425			// In Unique chain, any token can have any amount of approved users, so we need to426			// set allowance of old owner to 0427			if let Some(old_spender) = old_spender {428				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(429					collection.id,430					token,431					sender.clone(),432					old_spender.clone(),433					0,434				));435			}436		}437	}438439	pub fn set_allowance(440		collection: &NonfungibleHandle<T>,441		sender: &T::CrossAccountId,442		token: TokenId,443		spender: Option<&T::CrossAccountId>,444	) -> DispatchResult {445		if collection.access == AccessMode::AllowList {446			collection.check_allowlist(&sender)?;447			if let Some(spender) = spender {448				collection.check_allowlist(&spender)?;449			}450		}451452		if let Some(spender) = spender {453			<PalletCommon<T>>::ensure_correct_receiver(spender)?;454		}455		let token_data =456			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;457		if &token_data.owner != sender {458			ensure!(459				collection.ignores_owned_amount(sender),460				<CommonError<T>>::CantApproveMoreThanOwned461			);462		}463464		// =========465466		Self::set_allowance_unchecked(collection, sender, token, spender, false);467		Ok(())468	}469470	pub fn transfer_from(471		collection: &NonfungibleHandle<T>,472		spender: &T::CrossAccountId,473		from: &T::CrossAccountId,474		to: &T::CrossAccountId,475		token: TokenId,476	) -> DispatchResult {477		if spender.conv_eq(from) {478			return Self::transfer(collection, from, to, token);479		}480		if collection.access == AccessMode::AllowList {481			// `from`, `to` checked in [`transfer`]482			collection.check_allowlist(spender)?;483		}484485		if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {486			ensure!(487				collection.ignores_allowance(spender),488				<CommonError<T>>::TokenValueNotEnough489			);490		}491492		// =========493494		Self::transfer(collection, &from, to, token)?;495		// Allowance is reset in [`transfer`]496		Ok(())497	}498499	pub fn burn_from(500		collection: &NonfungibleHandle<T>,501		spender: &T::CrossAccountId,502		from: &T::CrossAccountId,503		token: TokenId,504	) -> DispatchResult {505		if spender.conv_eq(from) {506			return Self::burn(collection, from, token);507		}508		if collection.access == AccessMode::AllowList {509			// `from` checked in [`burn`]510			collection.check_allowlist(spender)?;511		}512513		if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {514			ensure!(515				collection.ignores_allowance(spender),516				<CommonError<T>>::TokenValueNotEnough517			);518		}519520		// =========521522		Self::burn(collection, &from, token)523	}524525	pub fn set_variable_metadata(526		collection: &NonfungibleHandle<T>,527		sender: &T::CrossAccountId,528		token: TokenId,529		data: Vec<u8>,530	) -> DispatchResult {531		ensure!(532			data.len() as u32 <= CUSTOM_DATA_LIMIT,533			<CommonError<T>>::TokenVariableDataLimitExceeded534		);535		let token_data =536			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;537		collection.check_can_update_meta(sender, &token_data.owner)?;538539		// =========540541		<TokenData<T>>::insert(542			(collection.id, token),543			ItemData {544				variable_data: data,545				..token_data546			},547		);548		Ok(())549	}550551	/// Delegated to `create_multiple_items`552	pub fn create_item(553		collection: &NonfungibleHandle<T>,554		sender: &T::CrossAccountId,555		data: CreateItemData<T>,556	) -> DispatchResult {557		Self::create_multiple_items(collection, sender, vec![data])558	}559}