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

difftreelog

source

pallets/structure/src/lib.rs12.6 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::{dispatch::DispatchResult, fail, pallet_prelude::*};57use pallet_common::{58	dispatch::CollectionDispatch, erc::CrossAccountId, eth::is_collection,59	CommonCollectionOperations,60};61use sp_std::collections::btree_set::BTreeSet;62use up_data_structs::{63	budget::Budget, mapping::TokenAddressMapping, CollectionId, TokenId, TokenOwnerError,64};6566#[cfg(feature = "runtime-benchmarks")]67pub mod benchmarking;68pub mod weights;6970pub use pallet::*;7172pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;7374#[frame_support::pallet]75pub mod pallet {76	use frame_support::{dispatch::GetDispatchInfo, traits::UnfilteredDispatchable, Parameter};7778	use super::*;7980	#[pallet::error]81	pub enum Error<T> {82		/// While nesting, encountered an already checked account, detecting a loop.83		OuroborosDetected,84		/// While nesting, reached the depth limit of nesting, exceeding the provided budget.85		DepthLimit,86		/// While nesting, reached the breadth limit of nesting, exceeding the provided budget.87		BreadthLimit,88		/// Couldn't find the token owner that is itself a token.89		TokenNotFound,90		/// Tried to nest token under collection contract address, instead of token address91		CantNestTokenUnderCollection,92	}9394	#[pallet::event]95	pub enum Event<T> {96		/// Executed call on behalf of the token.97		Executed(DispatchResult),98	}99100	#[pallet::config]101	pub trait Config: frame_system::Config + pallet_common::Config {102		type WeightInfo: weights::WeightInfo;103		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;104		type RuntimeCall: Parameter105			+ UnfilteredDispatchable<RuntimeOrigin = Self::RuntimeOrigin>106			+ GetDispatchInfo;107	}108109	#[pallet::pallet]110	pub struct Pallet<T>(_);111112	#[pallet::call]113	impl<T: Config> Pallet<T> {114		// #[pallet::weight({115		// 	let dispatch_info = call.get_dispatch_info();116117		// 	(118		// 		dispatch_info.weight119		// 			// Cost of dereferencing parent120		// 			.saturating_add(T::DbWeight::get().reads(2 * *max_depth as Weight))121		// 			.saturating_add(4000 * *max_depth as Weight),122		// 		dispatch_info.class)123		// })]124		// pub fn execute(125		// 	origin: OriginFor<T>,126		// 	call: Box<<T as Config>::Call>,127		// 	max_depth: u32,128		// ) -> DispatchResult {129	}130}131132#[derive(PartialEq)]133pub enum Parent<CrossAccountId> {134	/// Token owned by a normal account.135	User(CrossAccountId),136	/// Could not find the token provided as the owner.137	TokenNotFound,138	/// Nested token has multiple owners.139	MultipleOwners,140	/// Token owner is another token (still, the target token may not exist).141	Token(CollectionId, TokenId),142}143144impl<T: Config> Pallet<T> {145	/// Find account owning the `token` or a token that the `token` is nested in.146	///147	/// Returns the enum that have three variants:148	/// - [`User`](crate::Parent<T>::User): Contains account.149	/// - [`Token`](crate::Parent<T>::Token): Contains token id and collection id.150	/// - [`TokenNotFound`](crate::Parent<T>::TokenNotFound): Indicates that parent was not found151	pub fn find_parent(152		collection: CollectionId,153		token: TokenId,154	) -> Result<Parent<T::CrossAccountId>, DispatchError> {155		// TODO: Reduce cost by not reading collection config156		let handle = match T::CollectionDispatch::dispatch(collection) {157			Ok(v) => v,158			Err(_) => return Ok(Parent::TokenNotFound),159		};160		let handle = handle.as_dyn();161162		Ok(match handle.token_owner(token) {163			Ok(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {164				Some((collection, token)) => Parent::Token(collection, token),165				None => Parent::User(owner),166			},167			Err(TokenOwnerError::MultipleOwners) => Parent::MultipleOwners,168			Err(TokenOwnerError::NotFound) => Parent::TokenNotFound,169		})170	}171172	/// Get the chain of parents of a token in the nesting hierarchy173	///174	/// Returns an iterator of addresses of the owning tokens and the owning account,175	/// starting from the immediate parent token, ending with the account.176	/// Returns error if cycle is detected.177	pub fn parent_chain(178		mut collection: CollectionId,179		mut token: TokenId,180	) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {181		let mut finished = false;182		let mut visited = BTreeSet::new();183		visited.insert((collection, token));184		core::iter::from_fn(move || {185			if finished {186				return None;187			}188			let parent = Self::find_parent(collection, token);189			match parent {190				Ok(Parent::Token(new_collection, new_token)) => {191					collection = new_collection;192					token = new_token;193					if !visited.insert((new_collection, new_token)) {194						finished = true;195						return Some(Err(<Error<T>>::OuroborosDetected.into()));196					}197				}198				_ => finished = true,199			}200			Some(parent as Result<_, DispatchError>)201		})202	}203204	/// Try to dereference address, until finding top level owner205	///206	/// May return token address if parent token not yet exists207	///208	/// Returns `None` if the token has multiple owners.209	///210	/// - `budget`: Limit for searching parents in depth.211	pub fn find_topmost_owner(212		collection: CollectionId,213		token: TokenId,214		budget: &dyn Budget,215	) -> Result<Option<T::CrossAccountId>, DispatchError> {216		let owner = Self::parent_chain(collection, token)217			.take_while(|_| budget.consume())218			.find(|p| {219				matches!(220					p,221					Ok(Parent::User(_) | Parent::TokenNotFound | Parent::MultipleOwners)222				)223			})224			.ok_or(<Error<T>>::DepthLimit)??;225226		Ok(match owner {227			Parent::User(v) => Some(v),228			Parent::MultipleOwners => None,229			_ => fail!(<Error<T>>::TokenNotFound),230		})231	}232233	/// Find the topmost parent and check that assigning `for_nest` token as a child for234	/// `token` wouldn't create a cycle.235	///236	/// Returns `None` if the token has multiple owners.237	///238	/// - `budget`: Limit for searching parents in depth.239	pub fn get_checked_topmost_owner(240		collection: CollectionId,241		token: TokenId,242		for_nest: Option<(CollectionId, TokenId)>,243		budget: &dyn Budget,244	) -> Result<Option<T::CrossAccountId>, DispatchError> {245		// Tried to nest token in itself246		if Some((collection, token)) == for_nest {247			return Err(<Error<T>>::OuroborosDetected.into());248		}249250		for parent in Self::parent_chain(collection, token).take_while(|_| budget.consume()) {251			match parent? {252				// Tried to nest token in chain, which has this token as one of parents253				Parent::Token(collection, token) if Some((collection, token)) == for_nest => {254					return Err(<Error<T>>::OuroborosDetected.into())255				}256				// Token is owned by other user257				Parent::User(user) => return Ok(Some(user)),258				Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),259				Parent::MultipleOwners => return Ok(None),260				// Continue parent chain261				Parent::Token(_, _) => {}262			}263		}264265		Err(<Error<T>>::DepthLimit.into())266	}267268	/// Check if `token` indirectly owned by `user`269	///270	/// Returns `true` if `user` is `token`'s owner. Or If token is provided as `user` then271	/// check that `user` and `token` have same owner.272	/// Checks that assigning `for_nest` token as a child for `token` wouldn't create a cycle.273	///274	/// - `budget`: Limit for searching parents in depth.275	pub fn check_indirectly_owned(276		user: T::CrossAccountId,277		collection: CollectionId,278		token: TokenId,279		for_nest: Option<(CollectionId, TokenId)>,280		budget: &dyn Budget,281	) -> Result<bool, DispatchError> {282		let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {283			Some((collection, token)) => match Self::find_topmost_owner(collection, token, budget)?284			{285				Some(topmost_owner) => topmost_owner,286				None => return Ok(false),287			},288			None => user,289		};290291		Self::get_checked_topmost_owner(collection, token, for_nest, budget).map(|indirect_owner| {292			indirect_owner.map_or(false, |indirect_owner| indirect_owner == target_parent)293		})294	}295296	/// Checks that `under` is valid token and that `token_id` could be nested under it297	/// and that `from` is `under`'s owner298	///299	/// Returns OK if `under` is not a token300	///301	/// - `nesting_budget`: Limit for searching parents in depth.302	pub fn check_nesting(303		from: &T::CrossAccountId,304		under: &T::CrossAccountId,305		collection_id: CollectionId,306		token_id: TokenId,307		nesting_budget: &dyn Budget,308	) -> DispatchResult {309		Self::try_exec_if_token(under, |collection, parent_id| {310			collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)311		})312	}313314	/// Nests `token_id` under `under` token315	///316	/// Returns OK if `under` is not a token. Checks that nesting is possible.317	///318	/// - `nesting_budget`: Limit for searching parents in depth.319	pub fn nest_if_sent_to_token(320		from: &T::CrossAccountId,321		under: &T::CrossAccountId,322		collection_id: CollectionId,323		token_id: TokenId,324		nesting_budget: &dyn Budget,325	) -> DispatchResult {326		Self::try_exec_if_token(under, |collection, parent_id| {327			collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)?;328329			collection.nest(parent_id, (collection_id, token_id));330331			Ok(())332		})333	}334335	/// Nests `token_id` under `owner` token336	///337	/// Caller should check that nesting wouldn't cause recursion in nesting338	pub fn nest_if_sent_to_token_unchecked(339		owner: &T::CrossAccountId,340		collection_id: CollectionId,341		token_id: TokenId,342	) {343		Self::exec_if_token(owner, |collection, parent_id| {344			collection.nest(parent_id, (collection_id, token_id))345		});346	}347348	/// Unnests `token_id` from `owner`.349	pub fn unnest_if_nested(350		owner: &T::CrossAccountId,351		collection_id: CollectionId,352		token_id: TokenId,353	) {354		if let Err(e) = Self::try_exec_if_token(owner, |collection, parent_id| {355			collection.unnest(parent_id, (collection_id, token_id));356			Ok(())357		}) {358			log::warn!("unnest precondition failed: {e:?}")359		}360	}361362	/// # Panics363	/// If [`Self::try_exec_if_token`] fails364	fn exec_if_token(365		account: &T::CrossAccountId,366		action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId),367	) {368		Self::try_exec_if_token(account, |collection, id| {369			action(collection, id);370			Ok(())371		})372		.unwrap();373	}374375	/// If `account` is a token address, execute `action` providing found collection as an argument376	/// Token may not exist, it is expected it will be checked in the callback.377	fn try_exec_if_token(378		account: &T::CrossAccountId,379		action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,380	) -> DispatchResult {381		if is_collection(account.as_eth()) {382			fail!(<Error<T>>::CantNestTokenUnderCollection);383		}384		let Some((collection, token)) = T::CrossTokenAddressMapping::address_to_token(account)385		else {386			return Ok(());387		};388389		let dispatch = T::CollectionDispatch::dispatch(collection)?;390		let dispatch = dispatch.as_dyn();391392		action(dispatch, token)393	}394}