git.delta.rocks / unique-network / refs/commits / 82cba6b103c9

difftreelog

source

pallets/structure/src/lib.rs13.5 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 pallet_common::CommonCollectionOperations;57use pallet_common::{erc::CrossAccountId, eth::is_collection};58use sp_std::collections::btree_set::BTreeSet;5960use frame_support::dispatch::{DispatchError, DispatchResult, DispatchResultWithPostInfo};61use frame_support::fail;62pub use pallet::*;63use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};64use up_data_structs::CollectionMode;65use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};6667#[cfg(feature = "runtime-benchmarks")]68pub mod benchmarking;69pub mod weights;7071pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;7273#[frame_support::pallet]74pub mod pallet {75	use frame_support::Parameter;76	use frame_support::dispatch::{GetDispatchInfo, UnfilteredDispatchable};77	use frame_support::pallet_prelude::*;7879	use super::*;8081	#[pallet::error]82	pub enum Error<T> {83		/// While nesting, encountered an already checked account, detecting a loop.84		OuroborosDetected,85		/// While nesting, reached the depth limit of nesting, exceeding the provided budget.86		DepthLimit,87		/// While nesting, reached the breadth limit of nesting, exceeding the provided budget.88		BreadthLimit,89		/// Couldn't find the token owner that is itself a token.90		TokenNotFound,91		/// Tried to nest token under collection contract address, instead of token address92		CantNestTokenUnderCollection,93	}9495	#[pallet::event]96	pub enum Event<T> {97		/// Executed call on behalf of the token.98		Executed(DispatchResult),99	}100101	#[pallet::config]102	pub trait Config: frame_system::Config + pallet_common::Config {103		type WeightInfo: weights::WeightInfo;104		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;105		type RuntimeCall: Parameter106			+ UnfilteredDispatchable<RuntimeOrigin = Self::RuntimeOrigin>107			+ GetDispatchInfo;108	}109110	#[pallet::pallet]111	pub struct Pallet<T>(_);112113	#[pallet::call]114	impl<T: Config> Pallet<T> {115		// #[pallet::weight({116		// 	let dispatch_info = call.get_dispatch_info();117118		// 	(119		// 		dispatch_info.weight120		// 			// Cost of dereferencing parent121		// 			.saturating_add(T::DbWeight::get().reads(2 * *max_depth as Weight))122		// 			.saturating_add(4000 * *max_depth as Weight),123		// 		dispatch_info.class)124		// })]125		// pub fn execute(126		// 	origin: OriginFor<T>,127		// 	call: Box<<T as Config>::Call>,128		// 	max_depth: u32,129		// ) -> DispatchResult {130	}131}132133#[derive(PartialEq)]134pub enum Parent<CrossAccountId> {135	/// Token owned by a normal account.136	User(CrossAccountId),137	/// Could not find the token provided as the owner.138	TokenNotFound,139	/// Nested token has multiple owners.140	MultipleOwners,141	/// Token owner is another token (still, the target token may not exist).142	Token(CollectionId, TokenId),143}144145impl<T: Config> Pallet<T> {146	/// Find account owning the `token` or a token that the `token` is nested in.147	///148	/// Returns the enum that have three variants:149	/// - [`User`](crate::Parent<T>::User): Contains account.150	/// - [`Token`](crate::Parent<T>::Token): Contains token id and collection id.151	/// - [`TokenNotFound`](crate::Parent<T>::TokenNotFound): Indicates that parent was not found152	pub fn find_parent(153		collection: CollectionId,154		token: TokenId,155	) -> Result<Parent<T::CrossAccountId>, DispatchError> {156		// TODO: Reduce cost by not reading collection config157		let handle = match CollectionHandle::try_get(collection) {158			Ok(v) => v,159			Err(_) => return Ok(Parent::TokenNotFound),160		};161		let handle = T::CollectionDispatch::dispatch(handle);162		let handle = handle.as_dyn();163164		Ok(match handle.token_owner(token) {165			Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {166				Some((collection, token)) => Parent::Token(collection, token),167				None => Parent::User(owner),168			},169			None if handle.mode() == CollectionMode::ReFungible => handle170				.total_pieces(token)171				.map(|_| Parent::MultipleOwners)172				.unwrap_or(Parent::TokenNotFound),173			None => Parent::TokenNotFound,174		})175	}176177	/// Get the chain of parents of a token in the nesting hierarchy178	///179	/// Returns an iterator of addresses of the owning tokens and the owning account,180	/// starting from the immediate parent token, ending with the account.181	/// Returns error if cycle is detected.182	pub fn parent_chain(183		mut collection: CollectionId,184		mut token: TokenId,185	) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {186		let mut finished = false;187		let mut visited = BTreeSet::new();188		visited.insert((collection, token));189		core::iter::from_fn(move || {190			if finished {191				return None;192			}193			let parent = Self::find_parent(collection, token);194			match parent {195				Ok(Parent::Token(new_collection, new_token)) => {196					collection = new_collection;197					token = new_token;198					if !visited.insert((new_collection, new_token)) {199						finished = true;200						return Some(Err(<Error<T>>::OuroborosDetected.into()));201					}202				}203				_ => finished = true,204			}205			Some(parent as Result<_, DispatchError>)206		})207	}208209	/// Try to dereference address, until finding top level owner210	///211	/// May return token address if parent token not yet exists212	///213	/// Returns `None` if the token has multiple owners.214	///215	/// - `budget`: Limit for searching parents in depth.216	pub fn find_topmost_owner(217		collection: CollectionId,218		token: TokenId,219		budget: &dyn Budget,220	) -> Result<Option<T::CrossAccountId>, DispatchError> {221		let owner = Self::parent_chain(collection, token)222			.take_while(|_| budget.consume())223			.find(|p| {224				matches!(225					p,226					Ok(Parent::User(_) | Parent::TokenNotFound | Parent::MultipleOwners)227				)228			})229			.ok_or(<Error<T>>::DepthLimit)??;230231		Ok(match owner {232			Parent::User(v) => Some(v),233			Parent::MultipleOwners => None,234			_ => fail!(<Error<T>>::TokenNotFound),235		})236	}237238	/// Find the topmost parent and check that assigning `for_nest` token as a child for239	/// `token` wouldn't create a cycle.240	///241	/// Returns `None` if the token has multiple owners.242	///243	/// - `budget`: Limit for searching parents in depth.244	pub fn get_checked_topmost_owner(245		collection: CollectionId,246		token: TokenId,247		for_nest: Option<(CollectionId, TokenId)>,248		budget: &dyn Budget,249	) -> Result<Option<T::CrossAccountId>, DispatchError> {250		// Tried to nest token in itself251		if Some((collection, token)) == for_nest {252			return Err(<Error<T>>::OuroborosDetected.into());253		}254255		for parent in Self::parent_chain(collection, token).take_while(|_| budget.consume()) {256			match parent? {257				// Tried to nest token in chain, which has this token as one of parents258				Parent::Token(collection, token) if Some((collection, token)) == for_nest => {259					return Err(<Error<T>>::OuroborosDetected.into())260				}261				// Token is owned by other user262				Parent::User(user) => return Ok(Some(user)),263				Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),264				Parent::MultipleOwners => return Ok(None),265				// Continue parent chain266				Parent::Token(_, _) => {}267			}268		}269270		Err(<Error<T>>::DepthLimit.into())271	}272273	/// Burn token and all of it's nested tokens274	///275	/// - `self_budget`: Limit for searching children in depth.276	/// - `breadth_budget`: Limit of breadth of searching children.277	pub fn burn_item_recursively(278		from: T::CrossAccountId,279		collection: CollectionId,280		token: TokenId,281		self_budget: &dyn Budget,282		breadth_budget: &dyn Budget,283	) -> DispatchResultWithPostInfo {284		let handle = <CollectionHandle<T>>::try_get(collection)?;285		let dispatch = T::CollectionDispatch::dispatch(handle);286		let dispatch = dispatch.as_dyn();287		dispatch.burn_item_recursively(from.clone(), token, self_budget, breadth_budget)288	}289290	/// Check if `token` indirectly owned by `user`291	///292	/// Returns `true` if `user` is `token`'s owner. Or If token is provided as `user` then293	/// check that `user` and `token` have same owner.294	/// Checks that assigning `for_nest` token as a child for `token` wouldn't create a cycle.295	///296	/// - `budget`: Limit for searching parents in depth.297	pub fn check_indirectly_owned(298		user: T::CrossAccountId,299		collection: CollectionId,300		token: TokenId,301		for_nest: Option<(CollectionId, TokenId)>,302		budget: &dyn Budget,303	) -> Result<bool, DispatchError> {304		let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {305			Some((collection, token)) => match Self::find_topmost_owner(collection, token, budget)?306			{307				Some(topmost_owner) => topmost_owner,308				None => return Ok(false),309			},310			None => user,311		};312313		Self::get_checked_topmost_owner(collection, token, for_nest, budget).map(|indirect_owner| {314			indirect_owner.map_or(false, |indirect_owner| indirect_owner == target_parent)315		})316	}317318	/// Checks that `under` is valid token and that `token_id` could be nested under it319	/// and that `from` is `under`'s owner320	///321	/// Returns OK if `under` is not a token322	///323	/// - `nesting_budget`: Limit for searching parents in depth.324	pub fn check_nesting(325		from: T::CrossAccountId,326		under: &T::CrossAccountId,327		collection_id: CollectionId,328		token_id: TokenId,329		nesting_budget: &dyn Budget,330	) -> DispatchResult {331		Self::try_exec_if_token(under, |collection, parent_id| {332			collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)333		})334	}335336	/// Nests `token_id` under `under` token337	///338	/// Returns OK if `under` is not a token. Checks that nesting is possible.339	///340	/// - `nesting_budget`: Limit for searching parents in depth.341	pub fn nest_if_sent_to_token(342		from: T::CrossAccountId,343		under: &T::CrossAccountId,344		collection_id: CollectionId,345		token_id: TokenId,346		nesting_budget: &dyn Budget,347	) -> DispatchResult {348		Self::try_exec_if_token(under, |collection, parent_id| {349			collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)?;350351			collection.nest(parent_id, (collection_id, token_id));352353			Ok(())354		})355	}356357	/// Nests `token_id` under `owner` token358	///359	/// Caller should check that nesting wouldn't cause recursion in nesting360	pub fn nest_if_sent_to_token_unchecked(361		owner: &T::CrossAccountId,362		collection_id: CollectionId,363		token_id: TokenId,364	) {365		Self::exec_if_token(owner, |collection, parent_id| {366			collection.nest(parent_id, (collection_id, token_id))367		});368	}369370	/// Unnests `token_id` from `owner`.371	pub fn unnest_if_nested(372		owner: &T::CrossAccountId,373		collection_id: CollectionId,374		token_id: TokenId,375	) {376		if let Err(e) = Self::try_exec_if_token(owner, |collection, parent_id| {377			collection.unnest(parent_id, (collection_id, token_id));378			Ok(())379		}) {380			log::warn!("unnest precondition failed: {e:?}")381		}382	}383384	/// # Panics385	/// If [`Self::try_exec_if_token`] fails386	fn exec_if_token(387		account: &T::CrossAccountId,388		action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId),389	) {390		Self::try_exec_if_token(account, |collection, id| {391			action(collection, id);392			Ok(())393		})394		.unwrap();395	}396397	/// If `account` is a token address, execute `action` providing found collection as an argument398	/// Token may not exist, it is expected it will be checked in the callback.399	fn try_exec_if_token(400		account: &T::CrossAccountId,401		action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,402	) -> DispatchResult {403		if is_collection(&account.as_eth()) {404			fail!(<Error<T>>::CantNestTokenUnderCollection);405		}406		let Some((collection, token)) = T::CrossTokenAddressMapping::address_to_token(account) else {407			return Ok(())408		};409410		let handle = <CollectionHandle<T>>::try_get(collection)?;411412		let dispatch = T::CollectionDispatch::dispatch(handle);413		let dispatch = dispatch.as_dyn();414415		action(dispatch, token)416	}417}