git.delta.rocks / unique-network / refs/commits / 54cf3dbad6fe

difftreelog

source

pallets/common/src/lib.rs17.3 KiBsourcehistory
1#![cfg_attr(not(feature = "std"), no_std)]23use core::ops::{Deref, DerefMut};4use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};5use sp_std::vec::Vec;6use account::CrossAccountId;7use frame_support::{8	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo},9	ensure, fail,10	traits::{Imbalance, Get, Currency},11};12use pallet_evm::GasWeightMapping;13use up_data_structs::{14	COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,15	MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_COLLECTION_NAME_LENGTH, MAX_TOKEN_PREFIX_LENGTH,16	COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo, TokenId, Weight,17	WithdrawReasons, CollectionStats,18};19pub use pallet::*;20use sp_core::H160;21use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};22pub mod account;23#[cfg(feature = "runtime-benchmarks")]24pub mod benchmarking;25pub mod erc;26pub mod eth;2728#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]29pub struct CollectionHandle<T: Config> {30	pub id: CollectionId,31	collection: Collection<T::AccountId>,32	pub recorder: SubstrateRecorder<T>,33}34impl<T: Config> WithRecorder<T> for CollectionHandle<T> {35	fn recorder(&self) -> &SubstrateRecorder<T> {36		&self.recorder37	}38	fn into_recorder(self) -> SubstrateRecorder<T> {39		self.recorder40	}41}42impl<T: Config> CollectionHandle<T> {43	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {44		<CollectionById<T>>::get(id).map(|collection| Self {45			id,46			collection,47			recorder: SubstrateRecorder::new(eth::collection_id_to_address(id), gas_limit),48		})49	}50	pub fn new(id: CollectionId) -> Option<Self> {51		Self::new_with_gas_limit(id, u64::MAX)52	}53	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {54		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)55	}56	pub fn log_mirrored(&self, log: impl evm_coder::ToLog) {57		self.recorder.log_mirrored(log)58	}59	pub fn log_direct(&self, log: impl evm_coder::ToLog) {60		self.recorder.log_direct(log)61	}62	pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {63		self.recorder64			.consume_gas(T::GasWeightMapping::weight_to_gas(65				<T as frame_system::Config>::DbWeight::get()66					.read67					.saturating_mul(reads),68			))69	}70	pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {71		self.recorder72			.consume_gas(T::GasWeightMapping::weight_to_gas(73				<T as frame_system::Config>::DbWeight::get()74					.write75					.saturating_mul(writes),76			))77	}78	pub fn submit_logs(self) {79		self.recorder.submit_logs()80	}81	pub fn save(self) -> DispatchResult {82		self.recorder.submit_logs();83		<CollectionById<T>>::insert(self.id, self.collection);84		Ok(())85	}86}87impl<T: Config> Deref for CollectionHandle<T> {88	type Target = Collection<T::AccountId>;8990	fn deref(&self) -> &Self::Target {91		&self.collection92	}93}9495impl<T: Config> DerefMut for CollectionHandle<T> {96	fn deref_mut(&mut self) -> &mut Self::Target {97		&mut self.collection98	}99}100101impl<T: Config> CollectionHandle<T> {102	pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {103		ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);104		Ok(())105	}106	pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> bool {107		*subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject))108	}109	pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {110		ensure!(self.is_owner_or_admin(subject), <Error<T>>::NoPermission);111		Ok(())112	}113	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {114		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)115	}116	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {117		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)118	}119	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {120		ensure!(121			<Allowlist<T>>::get((self.id, user)),122			<Error<T>>::AddressNotInAllowlist123		);124		Ok(())125	}126127	pub fn check_can_update_meta(128		&self,129		subject: &T::CrossAccountId,130		item_owner: &T::CrossAccountId,131	) -> DispatchResult {132		match self.meta_update_permission {133			MetaUpdatePermission::ItemOwner => {134				ensure!(subject == item_owner, <Error<T>>::NoPermission);135				Ok(())136			}137			MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),138			MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),139		}140	}141}142143#[frame_support::pallet]144pub mod pallet {145	use super::*;146	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key};147	use account::CrossAccountId;148	use frame_support::traits::Currency;149	use up_data_structs::TokenId;150	use scale_info::TypeInfo;151152	#[pallet::config]153	pub trait Config: frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo {154		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;155156		type CrossAccountId: CrossAccountId<Self::AccountId>;157158		type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;159		type EvmBackwardsAddressMapping: up_evm_mapping::EvmBackwardsAddressMapping<Self::AccountId>;160161		type Currency: Currency<Self::AccountId>;162		type CollectionCreationPrice: Get<163			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,164		>;165		type TreasuryAccountId: Get<Self::AccountId>;166	}167168	#[pallet::pallet]169	#[pallet::generate_store(pub(super) trait Store)]170	pub struct Pallet<T>(_);171172	#[pallet::extra_constants]173	impl<T: Config> Pallet<T> {174		pub fn collection_admins_limit() -> u32 {175			COLLECTION_ADMINS_LIMIT176		}177	}178179	#[pallet::event]180	#[pallet::generate_deposit(pub fn deposit_event)]181	pub enum Event<T: Config> {182		/// New collection was created183		///184		/// # Arguments185		///186		/// * collection_id: Globally unique identifier of newly created collection.187		///188		/// * mode: [CollectionMode] converted into u8.189		///190		/// * account_id: Collection owner.191		CollectionCreated(CollectionId, u8, T::AccountId),192193		/// New collection was destroyed194		///195		/// # Arguments196		///197		/// * collection_id: Globally unique identifier of collection.198		CollectionDestroyed(CollectionId),199200		/// New item was created.201		///202		/// # Arguments203		///204		/// * collection_id: Id of the collection where item was created.205		///206		/// * item_id: Id of an item. Unique within the collection.207		///208		/// * recipient: Owner of newly created item209		///210		/// * amount: Always 1 for NFT211		ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),212213		/// Collection item was burned.214		///215		/// # Arguments216		///217		/// * collection_id.218		///219		/// * item_id: Identifier of burned NFT.220		///221		/// * owner: which user has destroyed its tokens222		///223		/// * amount: Always 1 for NFT224		ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),225226		/// Item was transferred227		///228		/// * collection_id: Id of collection to which item is belong229		///230		/// * item_id: Id of an item231		///232		/// * sender: Original owner of item233		///234		/// * recipient: New owner of item235		///236		/// * amount: Always 1 for NFT237		Transfer(238			CollectionId,239			TokenId,240			T::CrossAccountId,241			T::CrossAccountId,242			u128,243		),244245		/// * collection_id246		///247		/// * item_id248		///249		/// * sender250		///251		/// * spender252		///253		/// * amount254		Approved(255			CollectionId,256			TokenId,257			T::CrossAccountId,258			T::CrossAccountId,259			u128,260		),261	}262263	#[pallet::error]264	pub enum Error<T> {265		/// This collection does not exist.266		CollectionNotFound,267		/// Sender parameter and item owner must be equal.268		MustBeTokenOwner,269		/// No permission to perform action270		NoPermission,271		/// Collection is not in mint mode.272		PublicMintingNotAllowed,273		/// Address is not in allow list.274		AddressNotInAllowlist,275276		/// Collection name can not be longer than 63 char.277		CollectionNameLimitExceeded,278		/// Collection description can not be longer than 255 char.279		CollectionDescriptionLimitExceeded,280		/// Token prefix can not be longer than 15 char.281		CollectionTokenPrefixLimitExceeded,282		/// Total collections bound exceeded.283		TotalCollectionsLimitExceeded,284		/// variable_data exceeded data limit.285		TokenVariableDataLimitExceeded,286		/// Exceeded max admin count287		CollectionAdminCountExceeded,288289		/// Collection settings not allowing items transferring290		TransferNotAllowed,291		/// Account token limit exceeded per collection292		AccountTokenLimitExceeded,293		/// Collection token limit exceeded294		CollectionTokenLimitExceeded,295		/// Metadata flag frozen296		MetadataFlagFrozen,297298		/// Item not exists.299		TokenNotFound,300		/// Item balance not enough.301		TokenValueTooLow,302		/// Requested value more than approved.303		TokenValueNotEnough,304		/// Tried to approve more than owned305		CantApproveMoreThanOwned,306307		/// Can't transfer tokens to ethereum zero address308		AddressIsZero,309		/// Target collection doesn't supports this operation310		UnsupportedOperation,311	}312313	#[pallet::storage]314	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;315	#[pallet::storage]316	pub type DestroyedCollectionCount<T> =317		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;318319	/// Collection info320	#[pallet::storage]321	pub type CollectionById<T> = StorageMap<322		Hasher = Blake2_128Concat,323		Key = CollectionId,324		Value = Collection<<T as frame_system::Config>::AccountId>,325		QueryKind = OptionQuery,326	>;327328	#[pallet::storage]329	pub type AdminAmount<T> = StorageMap<330		Hasher = Blake2_128Concat,331		Key = CollectionId,332		Value = u32,333		QueryKind = ValueQuery,334	>;335336	/// List of collection admins337	#[pallet::storage]338	pub type IsAdmin<T: Config> = StorageNMap<339		Key = (340			Key<Blake2_128Concat, CollectionId>,341			Key<Blake2_128Concat, T::CrossAccountId>,342		),343		Value = bool,344		QueryKind = ValueQuery,345	>;346347	/// Allowlisted collection users348	#[pallet::storage]349	pub type Allowlist<T: Config> = StorageNMap<350		Key = (351			Key<Blake2_128Concat, CollectionId>,352			Key<Blake2_128Concat, T::CrossAccountId>,353		),354		Value = bool,355		QueryKind = ValueQuery,356	>;357358	/// Not used by code, exists only to provide some types to metadata359	#[pallet::storage]360	pub type DummyStorageValue<T> =361		StorageValue<Value = (CollectionStats, CollectionId, TokenId), QueryKind = OptionQuery>;362}363364impl<T: Config> Pallet<T> {365	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens366	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {367		ensure!(368			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,369			<Error<T>>::AddressIsZero370		);371		Ok(())372	}373	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {374		<IsAdmin<T>>::iter_prefix((collection,))375			.map(|(a, _)| a)376			.collect()377	}378	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {379		<Allowlist<T>>::iter_prefix((collection,))380			.map(|(a, _)| a)381			.collect()382	}383	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {384		<Allowlist<T>>::get((collection, user))385	}386	pub fn collection_stats() -> CollectionStats {387		let created = <CreatedCollectionCount<T>>::get();388		let destroyed = <DestroyedCollectionCount<T>>::get();389		CollectionStats {390			created: created.0,391			destroyed: destroyed.0,392			alive: created.0 - destroyed.0,393		}394	}395}396397impl<T: Config> Pallet<T> {398	pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {399		{400			ensure!(401				data.name.len() <= MAX_COLLECTION_NAME_LENGTH,402				Error::<T>::CollectionNameLimitExceeded403			);404			ensure!(405				data.description.len() <= MAX_COLLECTION_DESCRIPTION_LENGTH,406				Error::<T>::CollectionDescriptionLimitExceeded407			);408			ensure!(409				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH,410				Error::<T>::CollectionTokenPrefixLimitExceeded411			);412		}413414		let created_count = <CreatedCollectionCount<T>>::get()415			.0416			.checked_add(1)417			.ok_or(ArithmeticError::Overflow)?;418		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;419		let id = CollectionId(created_count);420421		// bound Total number of collections422		ensure!(423			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,424			<Error<T>>::TotalCollectionsLimitExceeded425		);426427		// =========428429		// Take a (non-refundable) deposit of collection creation430		{431			let mut imbalance =432				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();433			imbalance.subsume(434				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(435					&T::TreasuryAccountId::get(),436					T::CollectionCreationPrice::get(),437				),438			);439			<T as Config>::Currency::settle(440				&data.owner,441				imbalance,442				WithdrawReasons::TRANSFER,443				ExistenceRequirement::KeepAlive,444			)445			.map_err(|_| Error::<T>::NoPermission)?;446		}447448		<CreatedCollectionCount<T>>::put(created_count);449		<Pallet<T>>::deposit_event(Event::CollectionCreated(450			id,451			data.mode.id(),452			data.owner.clone(),453		));454		<CollectionById<T>>::insert(id, data);455		Ok(id)456	}457458	pub fn destroy_collection(459		collection: CollectionHandle<T>,460		sender: &T::CrossAccountId,461	) -> DispatchResult {462		ensure!(463			collection.limits.owner_can_destroy(),464			<Error<T>>::NoPermission,465		);466		collection.check_is_owner(sender)?;467468		let destroyed_collections = <DestroyedCollectionCount<T>>::get()469			.0470			.checked_add(1)471			.ok_or(ArithmeticError::Overflow)?;472473		// =========474475		<DestroyedCollectionCount<T>>::put(destroyed_collections);476		<CollectionById<T>>::remove(collection.id);477		<AdminAmount<T>>::remove(collection.id);478		<IsAdmin<T>>::remove_prefix((collection.id,), None);479		<Allowlist<T>>::remove_prefix((collection.id,), None);480481		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));482		Ok(())483	}484485	pub fn toggle_allowlist(486		collection: &CollectionHandle<T>,487		sender: &T::CrossAccountId,488		user: &T::CrossAccountId,489		allowed: bool,490	) -> DispatchResult {491		collection.check_is_owner_or_admin(sender)?;492493		// =========494495		if allowed {496			<Allowlist<T>>::insert((collection.id, user), true);497		} else {498			<Allowlist<T>>::remove((collection.id, user));499		}500501		Ok(())502	}503504	pub fn toggle_admin(505		collection: &CollectionHandle<T>,506		sender: &T::CrossAccountId,507		user: &T::CrossAccountId,508		admin: bool,509	) -> DispatchResult {510		collection.check_is_owner_or_admin(sender)?;511512		let was_admin = <IsAdmin<T>>::get((collection.id, user));513		if was_admin == admin {514			return Ok(());515		}516		let amount = <AdminAmount<T>>::get(collection.id);517518		if admin {519			let amount = amount520				.checked_add(1)521				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;522			ensure!(523				amount <= Self::collection_admins_limit(),524				<Error<T>>::CollectionAdminCountExceeded,525			);526527			// =========528529			<AdminAmount<T>>::insert(collection.id, amount);530			<IsAdmin<T>>::insert((collection.id, user), true);531		} else {532			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));533			<IsAdmin<T>>::remove((collection.id, user));534		}535536		Ok(())537	}538}539540#[macro_export]541macro_rules! unsupported {542	() => {543		Err(<Error<T>>::UnsupportedOperation.into())544	};545}546547/// Worst cases548pub trait CommonWeightInfo {549	fn create_item() -> Weight;550	fn create_multiple_items(amount: u32) -> Weight;551	fn burn_item() -> Weight;552	fn transfer() -> Weight;553	fn approve() -> Weight;554	fn transfer_from() -> Weight;555	fn burn_from() -> Weight;556	fn set_variable_metadata(bytes: u32) -> Weight;557}558559pub trait CommonCollectionOperations<T: Config> {560	fn create_item(561		&self,562		sender: T::CrossAccountId,563		to: T::CrossAccountId,564		data: CreateItemData,565	) -> DispatchResultWithPostInfo;566	fn create_multiple_items(567		&self,568		sender: T::CrossAccountId,569		to: T::CrossAccountId,570		data: Vec<CreateItemData>,571	) -> DispatchResultWithPostInfo;572	fn burn_item(573		&self,574		sender: T::CrossAccountId,575		token: TokenId,576		amount: u128,577	) -> DispatchResultWithPostInfo;578579	fn transfer(580		&self,581		sender: T::CrossAccountId,582		to: T::CrossAccountId,583		token: TokenId,584		amount: u128,585	) -> DispatchResultWithPostInfo;586	fn approve(587		&self,588		sender: T::CrossAccountId,589		spender: T::CrossAccountId,590		token: TokenId,591		amount: u128,592	) -> DispatchResultWithPostInfo;593	fn transfer_from(594		&self,595		sender: T::CrossAccountId,596		from: T::CrossAccountId,597		to: T::CrossAccountId,598		token: TokenId,599		amount: u128,600	) -> DispatchResultWithPostInfo;601	fn burn_from(602		&self,603		sender: T::CrossAccountId,604		from: T::CrossAccountId,605		token: TokenId,606		amount: u128,607	) -> DispatchResultWithPostInfo;608609	fn set_variable_metadata(610		&self,611		sender: T::CrossAccountId,612		token: TokenId,613		data: Vec<u8>,614	) -> DispatchResultWithPostInfo;615616	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;617	fn token_exists(&self, token: TokenId) -> bool;618	fn last_token_id(&self) -> TokenId;619620	fn token_owner(&self, token: TokenId) -> T::CrossAccountId;621	fn const_metadata(&self, token: TokenId) -> Vec<u8>;622	fn variable_metadata(&self, token: TokenId) -> Vec<u8>;623624	/// How many tokens collection contains (Applicable to nonfungible/refungible)625	fn collection_tokens(&self) -> u32;626	/// Amount of different tokens account has (Applicable to nonfungible/refungible)627	fn account_balance(&self, account: T::CrossAccountId) -> u32;628	/// Amount of specific token account have (Applicable to fungible/refungible)629	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;630	fn allowance(631		&self,632		sender: T::CrossAccountId,633		spender: T::CrossAccountId,634		token: TokenId,635	) -> u128;636}637638// Flexible enough for implementing CommonCollectionOperations639pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {640	let post_info = PostDispatchInfo {641		actual_weight: Some(weight),642		pays_fee: Pays::Yes,643	};644	match res {645		Ok(()) => Ok(post_info),646		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),647	}648}