git.delta.rocks / unique-network / refs/commits / 4275a8f9c142

difftreelog

source

pallets/structure/src/lib.rs13.2 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Structure Pallet18//!19//! The Structure pallet provides functionality for handling tokens nesting an unnesting.20//!21//! - [`Config`]22//! - [`Pallet`]23//!24//! ## Overview25//!26//! The Structure pallet provides functions for:27//!28//! - Searching for token parents, children and owners. Actual implementation of searching for29//!   parent/child is done by pallets corresponding to token's collection type.30//! - Nesting and unnesting tokens. Actual implementation of nesting is done by pallets corresponding31//!   to token's collection type.32//!33//! ### Terminology34//!35//! - **Nesting:** Setting up parent-child relationship between tokens. Nested tokens are inhereting36//!   owner from their parent. There could be multiple levels of nesting. Token couldn't be nested in37//!   it's child token i.e. parent-child relationship graph shouldn't have38//!39//! - **Parent:** Token that current token is nested in.40//!41//! - **Owner:** Account that owns the token and all nested tokens.42//!43//! ## Interface44//!45//! ### Available Functions46//!47//! - `find_parent` - Find parent of the token. It could be an account or another token.48//! - `parent_chain` - Find chain of parents of the token.49//! - `find_topmost_owner` - Find account or token in the end of the chain of parents.50//! - `check_nesting` - Check if the token could be nested in the other token51//! - `nest_if_sent_to_token` - Nest the token in the other token52//! - `unnest_if_nested` - Unnest the token from the other token5354#![cfg_attr(not(feature = "std"), no_std)]5556use frame_support::{57	dispatch::{DispatchResult, DispatchResultWithPostInfo},58	fail,59	pallet_prelude::*,60};61use pallet_common::{62	dispatch::CollectionDispatch, erc::CrossAccountId, eth::is_collection,63	CommonCollectionOperations,64};65use sp_std::collections::btree_set::BTreeSet;66use up_data_structs::{67	budget::Budget, mapping::TokenAddressMapping, CollectionId, TokenId, TokenOwnerError,68};6970#[cfg(feature = "runtime-benchmarks")]71pub mod benchmarking;72pub mod weights;7374pub use pallet::*;7576pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;7778#[frame_support::pallet]79pub mod pallet {80	use frame_support::{dispatch::GetDispatchInfo, traits::UnfilteredDispatchable, Parameter};8182	use super::*;8384	#[pallet::error]85	pub enum Error<T> {86		/// While nesting, encountered an already checked account, detecting a loop.87		OuroborosDetected,88		/// While nesting, reached the depth limit of nesting, exceeding the provided budget.89		DepthLimit,90		/// While nesting, reached the breadth limit of nesting, exceeding the provided budget.91		BreadthLimit,92		/// Couldn't find the token owner that is itself a token.93		TokenNotFound,94		/// Tried to nest token under collection contract address, instead of token address95		CantNestTokenUnderCollection,96	}9798	#[pallet::event]99	pub enum Event<T> {100		/// Executed call on behalf of the token.101		Executed(DispatchResult),102	}103104	#[pallet::config]105	pub trait Config: frame_system::Config + pallet_common::Config {106		type WeightInfo: weights::WeightInfo;107		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;108		type RuntimeCall: Parameter109			+ UnfilteredDispatchable<RuntimeOrigin = Self::RuntimeOrigin>110			+ GetDispatchInfo;111	}112113	#[pallet::pallet]114	pub struct Pallet<T>(_);115116	#[pallet::call]117	impl<T: Config> Pallet<T> {118		// #[pallet::weight({119		// 	let dispatch_info = call.get_dispatch_info();120121		// 	(122		// 		dispatch_info.weight123		// 			// Cost of dereferencing parent124		// 			.saturating_add(T::DbWeight::get().reads(2 * *max_depth as Weight))125		// 			.saturating_add(4000 * *max_depth as Weight),126		// 		dispatch_info.class)127		// })]128		// pub fn execute(129		// 	origin: OriginFor<T>,130		// 	call: Box<<T as Config>::Call>,131		// 	max_depth: u32,132		// ) -> DispatchResult {133	}134}135136#[derive(PartialEq)]137pub enum Parent<CrossAccountId> {138	/// Token owned by a normal account.139	User(CrossAccountId),140	/// Could not find the token provided as the owner.141	TokenNotFound,142	/// Nested token has multiple owners.143	MultipleOwners,144	/// Token owner is another token (still, the target token may not exist).145	Token(CollectionId, TokenId),146}147148impl<T: Config> Pallet<T> {149	/// Find account owning the `token` or a token that the `token` is nested in.150	///151	/// Returns the enum that have three variants:152	/// - [`User`](crate::Parent<T>::User): Contains account.153	/// - [`Token`](crate::Parent<T>::Token): Contains token id and collection id.154	/// - [`TokenNotFound`](crate::Parent<T>::TokenNotFound): Indicates that parent was not found155	pub fn find_parent(156		collection: CollectionId,157		token: TokenId,158	) -> Result<Parent<T::CrossAccountId>, DispatchError> {159		// TODO: Reduce cost by not reading collection config160		let handle = match T::CollectionDispatch::dispatch(collection) {161			Ok(v) => v,162			Err(_) => return Ok(Parent::TokenNotFound),163		};164		let handle = handle.as_dyn();165166		Ok(match handle.token_owner(token) {167			Ok(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {168				Some((collection, token)) => Parent::Token(collection, token),169				None => Parent::User(owner),170			},171			Err(TokenOwnerError::MultipleOwners) => Parent::MultipleOwners,172			Err(TokenOwnerError::NotFound) => Parent::TokenNotFound,173		})174	}175176	/// Get the chain of parents of a token in the nesting hierarchy177	///178	/// Returns an iterator of addresses of the owning tokens and the owning account,179	/// starting from the immediate parent token, ending with the account.180	/// Returns error if cycle is detected.181	pub fn parent_chain(182		mut collection: CollectionId,183		mut token: TokenId,184	) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {185		let mut finished = false;186		let mut visited = BTreeSet::new();187		visited.insert((collection, token));188		core::iter::from_fn(move || {189			if finished {190				return None;191			}192			let parent = Self::find_parent(collection, token);193			match parent {194				Ok(Parent::Token(new_collection, new_token)) => {195					collection = new_collection;196					token = new_token;197					if !visited.insert((new_collection, new_token)) {198						finished = true;199						return Some(Err(<Error<T>>::OuroborosDetected.into()));200					}201				}202				_ => finished = true,203			}204			Some(parent as Result<_, DispatchError>)205		})206	}207208	/// Try to dereference address, until finding top level owner209	///210	/// May return token address if parent token not yet exists211	///212	/// Returns `None` if the token has multiple owners.213	///214	/// - `budget`: Limit for searching parents in depth.215	pub fn find_topmost_owner(216		collection: CollectionId,217		token: TokenId,218		budget: &dyn Budget,219	) -> Result<Option<T::CrossAccountId>, DispatchError> {220		let owner = Self::parent_chain(collection, token)221			.take_while(|_| budget.consume())222			.find(|p| {223				matches!(224					p,225					Ok(Parent::User(_) | Parent::TokenNotFound | Parent::MultipleOwners)226				)227			})228			.ok_or(<Error<T>>::DepthLimit)??;229230		Ok(match owner {231			Parent::User(v) => Some(v),232			Parent::MultipleOwners => None,233			_ => fail!(<Error<T>>::TokenNotFound),234		})235	}236237	/// Find the topmost parent and check that assigning `for_nest` token as a child for238	/// `token` wouldn't create a cycle.239	///240	/// Returns `None` if the token has multiple owners.241	///242	/// - `budget`: Limit for searching parents in depth.243	pub fn get_checked_topmost_owner(244		collection: CollectionId,245		token: TokenId,246		for_nest: Option<(CollectionId, TokenId)>,247		budget: &dyn Budget,248	) -> Result<Option<T::CrossAccountId>, DispatchError> {249		// Tried to nest token in itself250		if Some((collection, token)) == for_nest {251			return Err(<Error<T>>::OuroborosDetected.into());252		}253254		for parent in Self::parent_chain(collection, token).take_while(|_| budget.consume()) {255			match parent? {256				// Tried to nest token in chain, which has this token as one of parents257				Parent::Token(collection, token) if Some((collection, token)) == for_nest => {258					return Err(<Error<T>>::OuroborosDetected.into())259				}260				// Token is owned by other user261				Parent::User(user) => return Ok(Some(user)),262				Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),263				Parent::MultipleOwners => return Ok(None),264				// Continue parent chain265				Parent::Token(_, _) => {}266			}267		}268269		Err(<Error<T>>::DepthLimit.into())270	}271272	/// Burn token and all of it's nested tokens273	///274	/// - `self_budget`: Limit for searching children in depth.275	/// - `breadth_budget`: Limit of breadth of searching children.276	pub fn burn_item_recursively(277		from: T::CrossAccountId,278		collection: CollectionId,279		token: TokenId,280		self_budget: &dyn Budget,281		breadth_budget: &dyn Budget,282	) -> DispatchResultWithPostInfo {283		let dispatch = T::CollectionDispatch::dispatch(collection)?;284		let dispatch = dispatch.as_dyn();285		dispatch.burn_item_recursively(from, token, self_budget, breadth_budget)286	}287288	/// Check if `token` indirectly owned by `user`289	///290	/// Returns `true` if `user` is `token`'s owner. Or If token is provided as `user` then291	/// check that `user` and `token` have same owner.292	/// Checks that assigning `for_nest` token as a child for `token` wouldn't create a cycle.293	///294	/// - `budget`: Limit for searching parents in depth.295	pub fn check_indirectly_owned(296		user: T::CrossAccountId,297		collection: CollectionId,298		token: TokenId,299		for_nest: Option<(CollectionId, TokenId)>,300		budget: &dyn Budget,301	) -> Result<bool, DispatchError> {302		let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {303			Some((collection, token)) => match Self::find_topmost_owner(collection, token, budget)?304			{305				Some(topmost_owner) => topmost_owner,306				None => return Ok(false),307			},308			None => user,309		};310311		Self::get_checked_topmost_owner(collection, token, for_nest, budget).map(|indirect_owner| {312			indirect_owner.map_or(false, |indirect_owner| indirect_owner == target_parent)313		})314	}315316	/// Checks that `under` is valid token and that `token_id` could be nested under it317	/// and that `from` is `under`'s owner318	///319	/// Returns OK if `under` is not a token320	///321	/// - `nesting_budget`: Limit for searching parents in depth.322	pub fn check_nesting(323		from: T::CrossAccountId,324		under: &T::CrossAccountId,325		collection_id: CollectionId,326		token_id: TokenId,327		nesting_budget: &dyn Budget,328	) -> DispatchResult {329		Self::try_exec_if_token(under, |collection, parent_id| {330			collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)331		})332	}333334	/// Nests `token_id` under `under` token335	///336	/// Returns OK if `under` is not a token. Checks that nesting is possible.337	///338	/// - `nesting_budget`: Limit for searching parents in depth.339	pub fn nest_if_sent_to_token(340		from: T::CrossAccountId,341		under: &T::CrossAccountId,342		collection_id: CollectionId,343		token_id: TokenId,344		nesting_budget: &dyn Budget,345	) -> DispatchResult {346		Self::try_exec_if_token(under, |collection, parent_id| {347			collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)?;348349			collection.nest(parent_id, (collection_id, token_id));350351			Ok(())352		})353	}354355	/// Nests `token_id` under `owner` token356	///357	/// Caller should check that nesting wouldn't cause recursion in nesting358	pub fn nest_if_sent_to_token_unchecked(359		owner: &T::CrossAccountId,360		collection_id: CollectionId,361		token_id: TokenId,362	) {363		Self::exec_if_token(owner, |collection, parent_id| {364			collection.nest(parent_id, (collection_id, token_id))365		});366	}367368	/// Unnests `token_id` from `owner`.369	pub fn unnest_if_nested(370		owner: &T::CrossAccountId,371		collection_id: CollectionId,372		token_id: TokenId,373	) {374		if let Err(e) = Self::try_exec_if_token(owner, |collection, parent_id| {375			collection.unnest(parent_id, (collection_id, token_id));376			Ok(())377		}) {378			log::warn!("unnest precondition failed: {e:?}")379		}380	}381382	/// # Panics383	/// If [`Self::try_exec_if_token`] fails384	fn exec_if_token(385		account: &T::CrossAccountId,386		action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId),387	) {388		Self::try_exec_if_token(account, |collection, id| {389			action(collection, id);390			Ok(())391		})392		.unwrap();393	}394395	/// If `account` is a token address, execute `action` providing found collection as an argument396	/// Token may not exist, it is expected it will be checked in the callback.397	fn try_exec_if_token(398		account: &T::CrossAccountId,399		action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,400	) -> DispatchResult {401		if is_collection(account.as_eth()) {402			fail!(<Error<T>>::CantNestTokenUnderCollection);403		}404		let Some((collection, token)) = T::CrossTokenAddressMapping::address_to_token(account)405		else {406			return Ok(());407		};408409		let dispatch = T::CollectionDispatch::dispatch(collection)?;410		let dispatch = dispatch.as_dyn();411412		action(dispatch, token)413	}414}