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

difftreelog

source

pallets/structure/src/lib.rs5.3 KiBsourcehistory
1#![cfg_attr(not(feature = "std"), no_std)]23use sp_std::collections::btree_set::BTreeSet;45use frame_support::dispatch::DispatchError;6use frame_support::fail;7pub use pallet::*;8use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};9use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};1011#[cfg(feature = "runtime-benchmarks")]12pub mod benchmarking;13pub mod weights;1415pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;1617#[frame_support::pallet]18pub mod pallet {19	use frame_support::Parameter;20	use frame_support::dispatch::{GetDispatchInfo, UnfilteredDispatchable};21	use frame_support::pallet_prelude::*;2223	use super::*;2425	#[pallet::error]26	pub enum Error<T> {27		/// While searched for owner, got already checked account28		OuroborosDetected,29		/// While searched for owner, encountered depth limit30		DepthLimit,31		/// While searched for owner, found token owner by not-yet-existing token32		TokenNotFound,33	}3435	#[pallet::event]36	pub enum Event<T> {37		/// Executed call on behalf of token38		Executed(DispatchResult),39	}4041	#[pallet::config]42	pub trait Config: frame_system::Config + pallet_common::Config {43		type WeightInfo: weights::WeightInfo;44		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;45		type Call: Parameter + UnfilteredDispatchable<Origin = Self::Origin> + GetDispatchInfo;46	}4748	#[pallet::pallet]49	pub struct Pallet<T>(_);5051	#[pallet::call]52	impl<T: Config> Pallet<T> {53		// #[pallet::weight({54		// 	let dispatch_info = call.get_dispatch_info();5556		// 	(57		// 		dispatch_info.weight58		// 			// Cost of dereferencing parent59		// 			.saturating_add(T::DbWeight::get().reads(2 * *max_depth as Weight))60		// 			.saturating_add(4000 * *max_depth as Weight),61		// 		dispatch_info.class)62		// })]63		// pub fn execute(64		// 	origin: OriginFor<T>,65		// 	call: Box<<T as Config>::Call>,66		// 	max_depth: u32,67		// ) -> DispatchResult {68	}69}7071#[derive(PartialEq)]72pub enum Parent<CrossAccountId> {73	/// Token owned by normal account74	User(CrossAccountId),75	/// Passed token not found76	TokenNotFound,77	/// Token owner is another token (target token still may not exist)78	Token(CollectionId, TokenId),79}8081impl<T: Config> Pallet<T> {82	pub fn find_parent(83		collection: CollectionId,84		token: TokenId,85	) -> Result<Parent<T::CrossAccountId>, DispatchError> {86		// TODO: Reduce cost by not reading collection config87		let handle = match CollectionHandle::try_get(collection) {88			Ok(v) => v,89			Err(_) => return Ok(Parent::TokenNotFound),90		};91		let handle = T::CollectionDispatch::dispatch(handle);92		let handle = handle.as_dyn();9394		Ok(match handle.token_owner(token) {95			Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {96				Some((collection, token)) => Parent::Token(collection, token),97				None => Parent::User(owner),98			},99			None => Parent::TokenNotFound,100		})101	}102103	pub fn parent_chain(104		mut collection: CollectionId,105		mut token: TokenId,106	) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {107		let mut finished = false;108		let mut visited = BTreeSet::new();109		visited.insert((collection, token));110		core::iter::from_fn(move || {111			if finished {112				return None;113			}114			let parent = Self::find_parent(collection, token);115			match parent {116				Ok(Parent::Token(new_collection, new_token)) => {117					collection = new_collection;118					token = new_token;119					if !visited.insert((new_collection, new_token)) {120						finished = true;121						return Some(Err(<Error<T>>::OuroborosDetected.into()));122					}123				}124				_ => finished = true,125			}126			Some(parent as Result<_, DispatchError>)127		})128	}129130	/// Try to dereference address, until finding top level owner131	///132	/// May return token address if parent token not yet exists133	pub fn find_topmost_owner(134		collection: CollectionId,135		token: TokenId,136		budget: &dyn Budget,137	) -> Result<T::CrossAccountId, DispatchError> {138		let owner = Self::parent_chain(collection, token)139			.take_while(|_| budget.consume())140			.find(|p| matches!(p, Ok(Parent::User(_) | Parent::TokenNotFound)))141			.ok_or(<Error<T>>::DepthLimit)??;142143		Ok(match owner {144			Parent::User(v) => v,145			_ => fail!(<Error<T>>::TokenNotFound),146		})147	}148149	/// Check if token indirectly owned by specified user150	pub fn check_indirectly_owned(151		user: T::CrossAccountId,152		collection: CollectionId,153		token: TokenId,154		for_nest: Option<(CollectionId, TokenId)>,155		budget: &dyn Budget,156	) -> Result<bool, DispatchError> {157		let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {158			Some((collection, token)) => Parent::Token(collection, token),159			None => Parent::User(user),160		};161162		// Tried to nest token in itself163		if Some((collection, token)) == for_nest {164			return Err(<Error<T>>::OuroborosDetected.into());165		}166167		for parent in Self::parent_chain(collection, token).take_while(|_| budget.consume()) {168			match parent? {169				// Tried to nest token in chain, which has this token as one of parents170				Parent::Token(collection, token) if Some((collection, token)) == for_nest => {171					return Err(<Error<T>>::OuroborosDetected.into())172				}173				// Found needed parent, token is indirecty owned174				v if v == target_parent => return Ok(true),175				// Token is owned by other user176				Parent::User(_) => return Ok(false),177				Parent::TokenNotFound => return Ok(false),178				// Continue parent chain179				Parent::Token(_, _) => {}180			}181		}182183		Err(<Error<T>>::DepthLimit.into())184	}185}