git.delta.rocks / unique-network / refs/commits / 0fa7bd45c6ff

difftreelog

source

pallets/nonfungible/src/lib.rs15.2 KiBsourcehistory
1#![cfg_attr(not(feature = "std"), no_std)]23use erc::ERC721Events;4use frame_support::{BoundedVec, ensure};5use up_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 sp_core::H160;12use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};13use sp_std::{vec::Vec, vec};14use core::ops::Deref;15use sp_std::collections::btree_map::BTreeMap;16use codec::{Encode, Decode};17use scale_info::TypeInfo;1819pub use pallet::*;20#[cfg(feature = "runtime-benchmarks")]21pub mod benchmarking;22pub mod common;23pub mod erc;24pub mod weights;2526pub struct CreateItemData<T: Config> {27	pub const_data: BoundedVec<u8, CustomDataLimit>,28	pub variable_data: BoundedVec<u8, CustomDataLimit>,29	pub owner: T::CrossAccountId,30}31pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;3233#[derive(Encode, Decode, TypeInfo)]34pub struct ItemData<T: Config> {35	pub const_data: Vec<u8>,36	pub variable_data: Vec<u8>,37	pub owner: T::CrossAccountId,38}3940#[frame_support::pallet]41pub mod pallet {42	use super::*;43	use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};44	use up_data_structs::{CollectionId, TokenId};45	use super::weights::WeightInfo;4647	#[pallet::error]48	pub enum Error<T> {49		/// Not Nonfungible item data used to mint in Nonfungible collection.50		NotNonfungibleDataUsedToMintFungibleCollectionToken,51		/// Used amount > 1 with NFT52		NonfungibleItemsHaveNoAmount,53	}5455	#[pallet::config]56	pub trait Config: frame_system::Config + pallet_common::Config {57		type WeightInfo: WeightInfo;58	}5960	#[pallet::pallet]61	#[pallet::generate_store(pub(super) trait Store)]62	pub struct Pallet<T>(_);6364	#[pallet::storage]65	pub type TokensMinted<T: Config> =66		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;67	#[pallet::storage]68	pub type TokensBurnt<T: Config> =69		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;7071	#[pallet::storage]72	pub type TokenData<T: Config> = StorageNMap<73		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),74		Value = ItemData<T>,75		QueryKind = OptionQuery,76	>;7778	/// Used to enumerate tokens owned by account79	#[pallet::storage]80	pub type Owned<T: Config> = StorageNMap<81		Key = (82			Key<Twox64Concat, CollectionId>,83			Key<Blake2_128Concat, T::CrossAccountId>,84			Key<Twox64Concat, TokenId>,85		),86		Value = bool,87		QueryKind = ValueQuery,88	>;8990	#[pallet::storage]91	pub type AccountBalance<T: Config> = StorageNMap<92		Key = (93			Key<Twox64Concat, CollectionId>,94			Key<Blake2_128Concat, T::CrossAccountId>,95		),96		Value = u32,97		QueryKind = ValueQuery,98	>;99100	#[pallet::storage]101	pub type Allowance<T: Config> = StorageNMap<102		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),103		Value = T::CrossAccountId,104		QueryKind = OptionQuery,105	>;106}107108pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);109impl<T: Config> NonfungibleHandle<T> {110	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {111		Self(inner)112	}113	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {114		self.0115	}116}117impl<T: Config> Deref for NonfungibleHandle<T> {118	type Target = pallet_common::CollectionHandle<T>;119120	fn deref(&self) -> &Self::Target {121		&self.0122	}123}124125impl<T: Config> Pallet<T> {126	pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {127		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)128	}129	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {130		<TokenData<T>>::contains_key((collection.id, token))131	}132}133134// unchecked calls skips any permission checks135impl<T: Config> Pallet<T> {136	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {137		<PalletCommon<T>>::init_collection(data)138	}139	pub fn destroy_collection(140		collection: NonfungibleHandle<T>,141		sender: &T::CrossAccountId,142	) -> DispatchResult {143		let id = collection.id;144145		// =========146147		PalletCommon::destroy_collection(collection.0, sender)?;148149		<TokenData<T>>::remove_prefix((id,), None);150		<Owned<T>>::remove_prefix((id,), None);151		<TokensMinted<T>>::remove(id);152		<TokensBurnt<T>>::remove(id);153		<Allowance<T>>::remove_prefix((id,), None);154		<AccountBalance<T>>::remove_prefix((id,), None);155		Ok(())156	}157158	pub fn burn(159		collection: &NonfungibleHandle<T>,160		sender: &T::CrossAccountId,161		token: TokenId,162	) -> DispatchResult {163		let token_data = <TokenData<T>>::get((collection.id, token))164			.ok_or_else(|| <CommonError<T>>::TokenNotFound)?;165		ensure!(166			&token_data.owner == sender167				|| (collection.limits.owner_can_transfer()168					&& collection.is_owner_or_admin(sender)?),169			<CommonError<T>>::NoPermission170		);171172		if collection.access == AccessMode::AllowList {173			collection.check_allowlist(sender)?;174		}175176		let burnt = <TokensBurnt<T>>::get(collection.id)177			.checked_add(1)178			.ok_or(ArithmeticError::Overflow)?;179180		let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))181			.checked_sub(1)182			.ok_or(ArithmeticError::Overflow)?;183184		if balance == 0 {185			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));186		} else {187			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);188		}189		// =========190191		<Owned<T>>::remove((collection.id, &token_data.owner.clone(), token));192		<TokensBurnt<T>>::insert(collection.id, burnt);193		<TokenData<T>>::remove((collection.id, token));194		let old_spender = <Allowance<T>>::take((collection.id, token));195196		if let Some(old_spender) = old_spender {197			<PalletCommon<T>>::deposit_event(CommonEvent::Approved(198				collection.id,199				token,200				sender.clone(),201				old_spender.clone(),202				0,203			));204		}205206		collection.log_infallible(ERC721Events::Transfer {207			from: *token_data.owner.as_eth(),208			to: H160::default(),209			token_id: token.into(),210		});211		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(212			collection.id,213			token,214			token_data.owner,215			1,216		));217		return Ok(());218	}219220	pub fn transfer(221		collection: &NonfungibleHandle<T>,222		from: &T::CrossAccountId,223		to: &T::CrossAccountId,224		token: TokenId,225	) -> DispatchResult {226		ensure!(227			collection.limits.transfers_enabled(),228			<CommonError<T>>::TransferNotAllowed229		);230231		let token_data = <TokenData<T>>::get((collection.id, token))232			.ok_or_else(|| <CommonError<T>>::TokenNotFound)?;233		ensure!(234			&token_data.owner == from235				|| (collection.limits.owner_can_transfer()236					&& collection.is_owner_or_admin(from)?),237			<CommonError<T>>::NoPermission238		);239240		if collection.access == AccessMode::AllowList {241			collection.check_allowlist(from)?;242			collection.check_allowlist(to)?;243		}244		<PalletCommon<T>>::ensure_correct_receiver(to)?;245246		let balance_from = <AccountBalance<T>>::get((collection.id, from))247			.checked_sub(1)248			.ok_or(<CommonError<T>>::TokenValueTooLow)?;249		let balance_to = if from != to {250			let balance_to = <AccountBalance<T>>::get((collection.id, to))251				.checked_add(1)252				.ok_or(ArithmeticError::Overflow)?;253254			ensure!(255				balance_to < collection.limits.account_token_ownership_limit(),256				<CommonError<T>>::AccountTokenLimitExceeded,257			);258259			Some(balance_to)260		} else {261			None262		};263264		collection.consume_sstores(4)?;265		collection.consume_log(3, 0)?;266267		// =========268269		<TokenData<T>>::insert(270			(collection.id, token),271			ItemData {272				owner: to.clone(),273				..token_data274			},275		);276277		if let Some(balance_to) = balance_to {278			// from != to279			if balance_from == 0 {280				<AccountBalance<T>>::remove((collection.id, from));281			} else {282				<AccountBalance<T>>::insert((collection.id, from), balance_from);283			}284			<AccountBalance<T>>::insert((collection.id, to), balance_to);285			<Owned<T>>::remove((collection.id, from, token));286			<Owned<T>>::insert((collection.id, to, token), true);287		}288		Self::set_allowance_unchecked(collection, from, token, None, true);289290		collection.log_infallible(ERC721Events::Transfer {291			from: *from.as_eth(),292			to: *to.as_eth(),293			token_id: token.into(),294		});295		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(296			collection.id,297			token,298			from.clone(),299			to.clone(),300			1,301		));302		Ok(())303	}304305	pub fn create_multiple_items(306		collection: &NonfungibleHandle<T>,307		sender: &T::CrossAccountId,308		data: Vec<CreateItemData<T>>,309	) -> DispatchResult {310		let unrestricted_minting = collection.is_owner_or_admin(sender)?;311		if !unrestricted_minting {312			ensure!(313				collection.mint_mode,314				<CommonError<T>>::PublicMintingNotAllowed315			);316			collection.check_allowlist(sender)?;317318			for item in data.iter() {319				collection.check_allowlist(&item.owner)?;320			}321		}322323		for data in data.iter() {324			<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;325			if !data.const_data.is_empty() {326				collection.consume_sstore()?;327			}328			if !data.variable_data.is_empty() {329				collection.consume_sstore()?;330			}331			collection.consume_sstore()?;332			collection.consume_log(3, 0)?;333		}334335		let first_token = <TokensMinted<T>>::get(collection.id);336		let tokens_minted = first_token337			.checked_add(data.len() as u32)338			.ok_or(ArithmeticError::Overflow)?;339		ensure!(340			tokens_minted <= collection.limits.token_limit(),341			<CommonError<T>>::CollectionTokenLimitExceeded342		);343		collection.consume_sstore()?;344345		let mut balances = BTreeMap::new();346		for data in &data {347			let balance = balances348				.entry(&data.owner)349				.or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));350			*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;351352			ensure!(353				*balance <= collection.limits.account_token_ownership_limit(),354				<CommonError<T>>::AccountTokenLimitExceeded,355			);356		}357		collection.consume_sstores(balances.len())?;358359		// =========360361		<TokensMinted<T>>::insert(collection.id, tokens_minted);362		for (account, balance) in balances {363			<AccountBalance<T>>::insert((collection.id, account), balance);364		}365		for (i, data) in data.into_iter().enumerate() {366			let token = first_token + i as u32 + 1;367368			<TokenData<T>>::insert(369				(collection.id, token),370				ItemData {371					const_data: data.const_data.into(),372					variable_data: data.variable_data.into(),373					owner: data.owner.clone(),374				},375			);376			<Owned<T>>::insert((collection.id, &data.owner, token), true);377378			collection.log_infallible(ERC721Events::Transfer {379				from: H160::default(),380				to: *data.owner.as_eth(),381				token_id: token.into(),382			});383			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(384				collection.id,385				TokenId(token),386				data.owner.clone(),387				1,388			));389		}390		Ok(())391	}392393	pub fn set_allowance_unchecked(394		collection: &NonfungibleHandle<T>,395		sender: &T::CrossAccountId,396		token: TokenId,397		spender: Option<&T::CrossAccountId>,398		assume_implicit_eth: bool,399	) {400		if let Some(spender) = spender {401			let old_spender = <Allowance<T>>::get((collection.id, token));402			<Allowance<T>>::insert((collection.id, token), spender);403			// In ERC721 there is only one possible approved user of token, so we set404			// approved user to spender405			collection.log_infallible(ERC721Events::Approval {406				owner: *sender.as_eth(),407				approved: *spender.as_eth(),408				token_id: token.into(),409			});410			// In Unique chain, any token can have any amount of approved users, so we need to411			// set allowance of old owner to 0, and allowance of new owner to 1412			if old_spender.as_ref() != Some(spender) {413				if let Some(old_owner) = old_spender {414					<PalletCommon<T>>::deposit_event(CommonEvent::Approved(415						collection.id,416						token,417						sender.clone(),418						old_owner.clone(),419						0,420					));421				}422				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(423					collection.id,424					token,425					sender.clone(),426					spender.clone(),427					1,428				));429			}430		} else {431			let old_spender = <Allowance<T>>::take((collection.id, token));432			if !assume_implicit_eth {433				// In ERC721 there is only one possible approved user of token, so we set434				// approved user to zero address435				collection.log_infallible(ERC721Events::Approval {436					owner: *sender.as_eth(),437					approved: H160::default(),438					token_id: token.into(),439				});440			}441			// In Unique chain, any token can have any amount of approved users, so we need to442			// set allowance of old owner to 0443			if let Some(old_spender) = old_spender {444				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(445					collection.id,446					token,447					sender.clone(),448					old_spender.clone(),449					0,450				));451			}452		}453	}454455	pub fn set_allowance(456		collection: &NonfungibleHandle<T>,457		sender: &T::CrossAccountId,458		token: TokenId,459		spender: Option<&T::CrossAccountId>,460	) -> DispatchResult {461		if collection.access == AccessMode::AllowList {462			collection.check_allowlist(&sender)?;463			if let Some(spender) = spender {464				collection.check_allowlist(&spender)?;465			}466		}467468		if let Some(spender) = spender {469			<PalletCommon<T>>::ensure_correct_receiver(spender)?;470		}471		let token_data =472			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;473		if &token_data.owner != sender {474			ensure!(475				collection.ignores_owned_amount(sender)?,476				<CommonError<T>>::CantApproveMoreThanOwned477			);478		}479480		// =========481482		Self::set_allowance_unchecked(collection, sender, token, spender, false);483		Ok(())484	}485486	pub fn transfer_from(487		collection: &NonfungibleHandle<T>,488		spender: &T::CrossAccountId,489		from: &T::CrossAccountId,490		to: &T::CrossAccountId,491		token: TokenId,492	) -> DispatchResult {493		if spender.conv_eq(from) {494			return Self::transfer(collection, from, to, token);495		}496		if collection.access == AccessMode::AllowList {497			// `from`, `to` checked in [`transfer`]498			collection.check_allowlist(spender)?;499		}500501		if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {502			ensure!(503				collection.ignores_allowance(spender)?,504				<CommonError<T>>::TokenValueNotEnough505			);506		}507508		// =========509510		Self::transfer(collection, &from, to, token)?;511		// Allowance is reset in [`transfer`]512		Ok(())513	}514515	pub fn burn_from(516		collection: &NonfungibleHandle<T>,517		spender: &T::CrossAccountId,518		from: &T::CrossAccountId,519		token: TokenId,520	) -> DispatchResult {521		if spender.conv_eq(from) {522			return Self::burn(collection, from, token);523		}524		if collection.access == AccessMode::AllowList {525			// `from` checked in [`burn`]526			collection.check_allowlist(spender)?;527		}528529		if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {530			ensure!(531				collection.ignores_allowance(spender)?,532				<CommonError<T>>::TokenValueNotEnough533			);534		}535536		// =========537538		Self::burn(collection, &from, token)539	}540541	pub fn set_variable_metadata(542		collection: &NonfungibleHandle<T>,543		sender: &T::CrossAccountId,544		token: TokenId,545		data: Vec<u8>,546	) -> DispatchResult {547		ensure!(548			data.len() as u32 <= CUSTOM_DATA_LIMIT,549			<CommonError<T>>::TokenVariableDataLimitExceeded550		);551		let token_data =552			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;553		collection.check_can_update_meta(sender, &token_data.owner)?;554555		collection.consume_sstore()?;556557		// =========558559		<TokenData<T>>::insert(560			(collection.id, token),561			ItemData {562				variable_data: data,563				..token_data564			},565		);566		Ok(())567	}568569	/// Delegated to `create_multiple_items`570	pub fn create_item(571		collection: &NonfungibleHandle<T>,572		sender: &T::CrossAccountId,573		data: CreateItemData<T>,574	) -> DispatchResult {575		Self::create_multiple_items(collection, sender, vec![data])576	}577}