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

difftreelog

source

pallets/structure/src/lib.rs8.1 KiBsourcehistory
1#![cfg_attr(not(feature = "std"), no_std)]23use pallet_common::CommonCollectionOperations;4use sp_std::collections::btree_set::BTreeSet;56use frame_support::dispatch::{DispatchError, DispatchResult, DispatchResultWithPostInfo};7use frame_support::fail;8pub use pallet::*;9use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};10use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};1112#[cfg(feature = "runtime-benchmarks")]13pub mod benchmarking;14pub mod weights;1516pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;1718#[frame_support::pallet]19pub mod pallet {20	use frame_support::Parameter;21	use frame_support::dispatch::{GetDispatchInfo, UnfilteredDispatchable};22	use frame_support::pallet_prelude::*;2324	use super::*;2526	#[pallet::error]27	pub enum Error<T> {28		/// While searched for owner, got already checked account29		OuroborosDetected,30		/// While searched for owner, encountered depth limit31		DepthLimit,32		/// While iterating over children, encountered breadth limit33		BreadthLimit,34		/// While searched for owner, found token owner by not-yet-existing token35		TokenNotFound,36	}3738	#[pallet::event]39	pub enum Event<T> {40		/// Executed call on behalf of token41		Executed(DispatchResult),42	}4344	#[pallet::config]45	pub trait Config: frame_system::Config + pallet_common::Config {46		type WeightInfo: weights::WeightInfo;47		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;48		type Call: Parameter + UnfilteredDispatchable<Origin = Self::Origin> + GetDispatchInfo;49	}5051	#[pallet::pallet]52	pub struct Pallet<T>(_);5354	#[pallet::call]55	impl<T: Config> Pallet<T> {56		// #[pallet::weight({57		// 	let dispatch_info = call.get_dispatch_info();5859		// 	(60		// 		dispatch_info.weight61		// 			// Cost of dereferencing parent62		// 			.saturating_add(T::DbWeight::get().reads(2 * *max_depth as Weight))63		// 			.saturating_add(4000 * *max_depth as Weight),64		// 		dispatch_info.class)65		// })]66		// pub fn execute(67		// 	origin: OriginFor<T>,68		// 	call: Box<<T as Config>::Call>,69		// 	max_depth: u32,70		// ) -> DispatchResult {71	}72}7374#[derive(PartialEq)]75pub enum Parent<CrossAccountId> {76	/// Token owned by normal account77	User(CrossAccountId),78	/// Passed token not found79	TokenNotFound,80	/// Token owner is another token (target token still may not exist)81	Token(CollectionId, TokenId),82}8384impl<T: Config> Pallet<T> {85	pub fn find_parent(86		collection: CollectionId,87		token: TokenId,88	) -> Result<Parent<T::CrossAccountId>, DispatchError> {89		// TODO: Reduce cost by not reading collection config90		let handle = match CollectionHandle::try_get(collection) {91			Ok(v) => v,92			Err(_) => return Ok(Parent::TokenNotFound),93		};94		let handle = T::CollectionDispatch::dispatch(handle);95		let handle = handle.as_dyn();9697		Ok(match handle.token_owner(token) {98			Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {99				Some((collection, token)) => Parent::Token(collection, token),100				None => Parent::User(owner),101			},102			None => Parent::TokenNotFound,103		})104	}105106	pub fn parent_chain(107		mut collection: CollectionId,108		mut token: TokenId,109	) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {110		let mut finished = false;111		let mut visited = BTreeSet::new();112		visited.insert((collection, token));113		core::iter::from_fn(move || {114			if finished {115				return None;116			}117			let parent = Self::find_parent(collection, token);118			match parent {119				Ok(Parent::Token(new_collection, new_token)) => {120					collection = new_collection;121					token = new_token;122					if !visited.insert((new_collection, new_token)) {123						finished = true;124						return Some(Err(<Error<T>>::OuroborosDetected.into()));125					}126				}127				_ => finished = true,128			}129			Some(parent as Result<_, DispatchError>)130		})131	}132133	/// Try to dereference address, until finding top level owner134	///135	/// May return token address if parent token not yet exists136	pub fn find_topmost_owner(137		collection: CollectionId,138		token: TokenId,139		budget: &dyn Budget,140	) -> Result<T::CrossAccountId, DispatchError> {141		let owner = Self::parent_chain(collection, token)142			.take_while(|_| budget.consume())143			.find(|p| matches!(p, Ok(Parent::User(_) | Parent::TokenNotFound)))144			.ok_or(<Error<T>>::DepthLimit)??;145146		Ok(match owner {147			Parent::User(v) => v,148			_ => fail!(<Error<T>>::TokenNotFound),149		})150	}151152	/// Check if token indirectly owned by specified user153	pub fn check_indirectly_owned(154		user: T::CrossAccountId,155		collection: CollectionId,156		token: TokenId,157		for_nest: Option<(CollectionId, TokenId)>,158		budget: &dyn Budget,159	) -> Result<bool, DispatchError> {160		let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {161			Some((collection, token)) => Self::find_topmost_owner(collection, token, budget)?,162			None => user,163		};164165		// Tried to nest token in itself166		if Some((collection, token)) == for_nest {167			return Err(<Error<T>>::OuroborosDetected.into());168		}169170		for parent in Self::parent_chain(collection, token).take_while(|_| budget.consume()) {171			match parent? {172				// Tried to nest token in chain, which has this token as one of parents173				Parent::Token(collection, token) if Some((collection, token)) == for_nest => {174					return Err(<Error<T>>::OuroborosDetected.into())175				}176				// Found needed parent, token is indirecty owned177				Parent::User(user) if user == target_parent => return Ok(true),178				// Token is owned by other user179				Parent::User(_) => return Ok(false),180				Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),181				// Continue parent chain182				Parent::Token(_, _) => {}183			}184		}185186		Err(<Error<T>>::DepthLimit.into())187	}188189	pub fn burn_item_recursively(190		from: T::CrossAccountId,191		collection: CollectionId,192		token: TokenId,193		self_budget: &dyn Budget,194		breadth_budget: &dyn Budget,195	) -> DispatchResultWithPostInfo {196		let handle = <CollectionHandle<T>>::try_get(collection)?;197		let dispatch = T::CollectionDispatch::dispatch(handle);198		let dispatch = dispatch.as_dyn();199		dispatch.burn_item_recursively(from.clone(), token, self_budget, breadth_budget)200	}201202	pub fn check_nesting(203		from: T::CrossAccountId,204		under: &T::CrossAccountId,205		collection_id: CollectionId,206		token_id: TokenId,207		nesting_budget: &dyn Budget,208	) -> DispatchResult {209		Self::try_exec_if_owner_is_valid_nft(under, |collection, parent_id| {210			collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)211		})212	}213214	pub fn nest_if_sent_to_token(215		from: T::CrossAccountId,216		under: &T::CrossAccountId,217		collection_id: CollectionId,218		token_id: TokenId,219		nesting_budget: &dyn Budget,220	) -> DispatchResult {221		Self::try_exec_if_owner_is_valid_nft(under, |collection, parent_id| {222			collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)?;223224			collection.nest(parent_id, (collection_id, token_id));225226			Ok(())227		})228	}229230	pub fn nest_if_sent_to_token_unchecked(231		owner: &T::CrossAccountId,232		collection_id: CollectionId,233		token_id: TokenId,234	) {235		Self::exec_if_owner_is_valid_nft(owner, |collection, parent_id| {236			collection.nest(parent_id, (collection_id, token_id))237		});238	}239240	pub fn unnest_if_nested(241		owner: &T::CrossAccountId,242		collection_id: CollectionId,243		token_id: TokenId,244	) {245		Self::exec_if_owner_is_valid_nft(owner, |collection, parent_id| {246			collection.unnest(parent_id, (collection_id, token_id))247		});248	}249250	fn exec_if_owner_is_valid_nft(251		account: &T::CrossAccountId,252		action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId),253	) {254		Self::try_exec_if_owner_is_valid_nft(account, |collection, id| {255			action(collection, id);256			Ok(())257		})258		.unwrap();259	}260261	fn try_exec_if_owner_is_valid_nft(262		account: &T::CrossAccountId,263		action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,264	) -> DispatchResult {265		let account = T::CrossTokenAddressMapping::address_to_token(account);266267		if account.is_none() {268			return Ok(());269		}270271		let account = account.unwrap();272273		let handle = <CollectionHandle<T>>::try_get(account.0);274275		if handle.is_err() {276			return Ok(());277		}278279		let handle = handle.unwrap();280281		let dispatch = T::CollectionDispatch::dispatch(handle);282		let dispatch = dispatch.as_dyn();283284		action(dispatch, account.1)285	}286}