git.delta.rocks / unique-network / refs/commits / 23942aa9dbcc

difftreelog

source

pallets/structure/src/lib.rs4.5 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};1011#[frame_support::pallet]12pub mod pallet {13	use frame_support::Parameter;14	use frame_support::dispatch::{GetDispatchInfo, UnfilteredDispatchable};15	use frame_support::pallet_prelude::*;16	use frame_system::pallet_prelude::*;1718	use super::*;1920	#[pallet::error]21	pub enum Error<T> {22		/// While searched for owner, got already checked account23		OuroborosDetected,24		/// While searched for owner, encountered depth limit25		DepthLimit,26		/// While searched for owner, found token owner by not-yet-existing token27		TokenNotFound,28	}2930	#[pallet::event]31	pub enum Event<T> {32		/// Executed call on behalf of token33		Executed(DispatchResult),34	}3536	#[pallet::config]37	pub trait Config: frame_system::Config + pallet_common::Config {38		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;39		type Call: Parameter + UnfilteredDispatchable<Origin = Self::Origin> + GetDispatchInfo;40	}4142	#[pallet::pallet]43	pub struct Pallet<T>(_);4445	#[pallet::call]46	impl<T: Config> Pallet<T> {47		// #[pallet::weight({48		// 	let dispatch_info = call.get_dispatch_info();4950		// 	(51		// 		dispatch_info.weight52		// 			// Cost of dereferencing parent53		// 			.saturating_add(T::DbWeight::get().reads(2 * *max_depth as Weight))54		// 			.saturating_add(4000 * *max_depth as Weight),55		// 		dispatch_info.class)56		// })]57		// pub fn execute(58		// 	origin: OriginFor<T>,59		// 	call: Box<<T as Config>::Call>,60		// 	max_depth: u32,61		// ) -> DispatchResult {62	}63}6465#[derive(PartialEq)]66pub enum Parent<CrossAccountId> {67	/// Token owned by normal account68	Normal(CrossAccountId),69	/// Passed token not found70	TokenNotFound,71	/// Token owner is another token (target token still may not exist)72	Token(CollectionId, TokenId),73}7475impl<T: Config> Pallet<T> {76	pub fn find_parent(77		collection: CollectionId,78		token: TokenId,79	) -> Result<Parent<T::CrossAccountId>, DispatchError> {80		// TODO: Reduce cost by not reading collection config81		let handle = match CollectionHandle::try_get(collection) {82			Ok(v) => v,83			Err(_) => return Ok(Parent::TokenNotFound),84		};85		let handle = T::CollectionDispatch::dispatch(handle);86		let handle = handle.as_dyn();8788		Ok(match handle.token_owner(token) {89			Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {90				Some((collection, token)) => Parent::Token(collection, token),91				None => Parent::Normal(owner),92			},93			None => Parent::TokenNotFound,94		})95	}9697	pub fn parent_chain(98		mut collection: CollectionId,99		mut token: TokenId,100	) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {101		let mut finished = false;102		let mut visited = BTreeSet::new();103		visited.insert((collection, token));104		core::iter::from_fn(move || {105			if finished {106				return None;107			}108			let parent = Self::find_parent(collection, token);109			match parent {110				Ok(Parent::Token(new_collection, new_token)) => {111					collection = new_collection;112					token = new_token;113					if !visited.insert((new_collection, new_token)) {114						finished = true;115						return Some(Err(<Error<T>>::OuroborosDetected.into()));116					}117				}118				_ => finished = true,119			}120			Some(parent as Result<_, DispatchError>)121		})122	}123124	/// Try to dereference address, until finding top level owner125	///126	/// May return token address if parent token not yet exists127	pub fn find_topmost_owner(128		collection: CollectionId,129		token: TokenId,130		max_depth: u32,131	) -> Result<T::CrossAccountId, DispatchError> {132		let owner = Self::parent_chain(collection, token)133			.take(max_depth as usize)134			.find(|p| matches!(p, Ok(Parent::Normal(_) | Parent::TokenNotFound)))135			.ok_or(<Error<T>>::DepthLimit)??;136137		Ok(match owner {138			Parent::Normal(v) => v,139			_ => fail!(<Error<T>>::TokenNotFound),140		})141	}142143	/// Check if token indirectly owned by specified user144	pub fn indirectly_owned(145		user: T::CrossAccountId,146		collection: CollectionId,147		token: TokenId,148		max_depth: u32,149	) -> Result<bool, DispatchError> {150		let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {151			Some((collection, token)) => Parent::Token(collection, token),152			None => Parent::Normal(user),153		};154155		Ok(Self::parent_chain(collection, token)156			.take(max_depth as usize)157			.any(|parent| Ok(&target_parent) == parent.as_ref()))158	}159}