git.delta.rocks / unique-network / refs/commits / 7563962a61ba

difftreelog

chore fixed code review request

Grigoriy Simonov2022-07-18parent: #59616c1.patch.diff
in: master

1 file changed

modifiedpallets/structure/src/lib.rsdiffbeforeafterboth
before · pallets/structure/src/lib.rs
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 sp_std::collections::btree_set::BTreeSet;5859use frame_support::dispatch::{DispatchError, DispatchResult, DispatchResultWithPostInfo};60use frame_support::fail;61pub use pallet::*;62use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};63use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};6465#[cfg(feature = "runtime-benchmarks")]66pub mod benchmarking;67pub mod weights;6869pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;7071#[frame_support::pallet]72pub mod pallet {73	use frame_support::Parameter;74	use frame_support::dispatch::{GetDispatchInfo, UnfilteredDispatchable};75	use frame_support::pallet_prelude::*;7677	use super::*;7879	#[pallet::error]80	pub enum Error<T> {81		/// While searched for owner, got already checked account82		OuroborosDetected,83		/// While searched for owner, encountered depth limit84		DepthLimit,85		/// While iterating over children, encountered breadth limit86		BreadthLimit,87		/// While searched for owner, found token owner by not-yet-existing token88		TokenNotFound,89	}9091	#[pallet::event]92	pub enum Event<T> {93		/// Executed call on behalf of token94		Executed(DispatchResult),95	}9697	#[pallet::config]98	pub trait Config: frame_system::Config + pallet_common::Config {99		type WeightInfo: weights::WeightInfo;100		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;101		type Call: Parameter + UnfilteredDispatchable<Origin = Self::Origin> + GetDispatchInfo;102	}103104	#[pallet::pallet]105	pub struct Pallet<T>(_);106107	#[pallet::call]108	impl<T: Config> Pallet<T> {109		// #[pallet::weight({110		// 	let dispatch_info = call.get_dispatch_info();111112		// 	(113		// 		dispatch_info.weight114		// 			// Cost of dereferencing parent115		// 			.saturating_add(T::DbWeight::get().reads(2 * *max_depth as Weight))116		// 			.saturating_add(4000 * *max_depth as Weight),117		// 		dispatch_info.class)118		// })]119		// pub fn execute(120		// 	origin: OriginFor<T>,121		// 	call: Box<<T as Config>::Call>,122		// 	max_depth: u32,123		// ) -> DispatchResult {124	}125}126127#[derive(PartialEq)]128pub enum Parent<CrossAccountId> {129	/// Token owned by normal account130	User(CrossAccountId),131	/// Passed token not found132	TokenNotFound,133	/// Token owner is another token (target token still may not exist)134	Token(CollectionId, TokenId),135}136137impl<T: Config> Pallet<T> {138	/// Find account owning the `token` or a token that the `token` is nested in.139	///140	/// Returns the enum that have three variants:141	/// - [`User`](crate::Parent<T>::User): Contains account.142	/// - [`Token`](crate::Parent<T>::Token): Contains token id and collection id.143	/// - [`TokenNotFound`](crate::Parent<T>::TokenNotFound): Indicates that parent was not found144	pub fn find_parent(145		collection: CollectionId,146		token: TokenId,147	) -> Result<Parent<T::CrossAccountId>, DispatchError> {148		// TODO: Reduce cost by not reading collection config149		let handle = match CollectionHandle::try_get(collection) {150			Ok(v) => v,151			Err(_) => return Ok(Parent::TokenNotFound),152		};153		let handle = T::CollectionDispatch::dispatch(handle);154		let handle = handle.as_dyn();155156		Ok(match handle.token_owner(token) {157			Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {158				Some((collection, token)) => Parent::Token(collection, token),159				None => Parent::User(owner),160			},161			None => Parent::TokenNotFound,162		})163	}164165	/// Find chain of parents of current token166	///167	/// Returns the parent of the current token, than the parent of the parent and so on until token without a parent168	/// is returned. Returns error if cycle is detected.169	pub fn parent_chain(170		mut collection: CollectionId,171		mut token: TokenId,172	) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {173		let mut finished = false;174		let mut visited = BTreeSet::new();175		visited.insert((collection, token));176		core::iter::from_fn(move || {177			if finished {178				return None;179			}180			let parent = Self::find_parent(collection, token);181			match parent {182				Ok(Parent::Token(new_collection, new_token)) => {183					collection = new_collection;184					token = new_token;185					if !visited.insert((new_collection, new_token)) {186						finished = true;187						return Some(Err(<Error<T>>::OuroborosDetected.into()));188					}189				}190				_ => finished = true,191			}192			Some(parent as Result<_, DispatchError>)193		})194	}195196	/// Try to dereference address, until finding top level owner197	///198	/// May return token address if parent token not yet exists199	///200	/// - `budget`: Limit for searching parents in depth.201	pub fn find_topmost_owner(202		collection: CollectionId,203		token: TokenId,204		budget: &dyn Budget,205	) -> Result<T::CrossAccountId, DispatchError> {206		let owner = Self::parent_chain(collection, token)207			.take_while(|_| budget.consume())208			.find(|p| matches!(p, Ok(Parent::User(_) | Parent::TokenNotFound)))209			.ok_or(<Error<T>>::DepthLimit)??;210211		Ok(match owner {212			Parent::User(v) => v,213			_ => fail!(<Error<T>>::TokenNotFound),214		})215	}216217	/// Find the topmost parent and check that assigning `for_nest` token as a child for218	/// `token` wouldn't create a cycle.219	///220	/// - `budget`: Limit for searching parents in depth.221	pub fn get_checked_topmost_owner(222		collection: CollectionId,223		token: TokenId,224		for_nest: Option<(CollectionId, TokenId)>,225		budget: &dyn Budget,226	) -> Result<T::CrossAccountId, DispatchError> {227		// Tried to nest token in itself228		if Some((collection, token)) == for_nest {229			return Err(<Error<T>>::OuroborosDetected.into());230		}231232		for parent in Self::parent_chain(collection, token).take_while(|_| budget.consume()) {233			match parent? {234				// Tried to nest token in chain, which has this token as one of parents235				Parent::Token(collection, token) if Some((collection, token)) == for_nest => {236					return Err(<Error<T>>::OuroborosDetected.into())237				}238				// Token is owned by other user239				Parent::User(user) => return Ok(user),240				Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),241				// Continue parent chain242				Parent::Token(_, _) => {}243			}244		}245246		Err(<Error<T>>::DepthLimit.into())247	}248249	/// Burn token and all of it's nested tokens250	///251	/// - `self_budget`: Limit for searching children in depth.252	/// - `breadth_budget`: Limit of breadth of searching children.253	pub fn burn_item_recursively(254		from: T::CrossAccountId,255		collection: CollectionId,256		token: TokenId,257		self_budget: &dyn Budget,258		breadth_budget: &dyn Budget,259	) -> DispatchResultWithPostInfo {260		let handle = <CollectionHandle<T>>::try_get(collection)?;261		let dispatch = T::CollectionDispatch::dispatch(handle);262		let dispatch = dispatch.as_dyn();263		dispatch.burn_item_recursively(from.clone(), token, self_budget, breadth_budget)264	}265266	/// Check if `token` indirectly owned by `user`267	///268	/// Returns `true` if `user` is `token`'s owner. Or If token is provided as `user` then269	/// check that `user` and `token` have same owner.270	/// Checks that assigning `for_nest` token as a child for `token` wouldn't create a cycle.271	///272	/// - `budget`: Limit for searching parents in depth.273	pub fn check_indirectly_owned(274		user: T::CrossAccountId,275		collection: CollectionId,276		token: TokenId,277		for_nest: Option<(CollectionId, TokenId)>,278		budget: &dyn Budget,279	) -> Result<bool, DispatchError> {280		let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {281			Some((collection, token)) => Self::find_topmost_owner(collection, token, budget)?,282			None => user,283		};284285		Self::get_checked_topmost_owner(collection, token, for_nest, budget)286			.map(|indirect_owner| indirect_owner == target_parent)287	}288289	/// Checks that `under` is valid token and that `token_id` could be nested under it290	/// and that `from` is `under`'s owner291	///292	/// Returns OK if `under` is not a token293	///294	/// - `nesting_budget`: Limit for searching parents in depth.295	pub fn check_nesting(296		from: T::CrossAccountId,297		under: &T::CrossAccountId,298		collection_id: CollectionId,299		token_id: TokenId,300		nesting_budget: &dyn Budget,301	) -> DispatchResult {302		Self::try_exec_if_owner_is_valid_nft(under, |collection, parent_id| {303			collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)304		})305	}306307	/// Nests `token_id` under `under` token308	///309	/// Returns OK if `under` is not a token. Checks that nesting is possible.310	///311	/// - `nesting_budget`: Limit for searching parents in depth.312	pub fn nest_if_sent_to_token(313		from: T::CrossAccountId,314		under: &T::CrossAccountId,315		collection_id: CollectionId,316		token_id: TokenId,317		nesting_budget: &dyn Budget,318	) -> DispatchResult {319		Self::try_exec_if_owner_is_valid_nft(under, |collection, parent_id| {320			collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)?;321322			collection.nest(parent_id, (collection_id, token_id));323324			Ok(())325		})326	}327328	/// Nests `token_id` under `owner` token329	///330	/// Caller should check that nesting wouldn't cause recursion in nesting331	pub fn nest_if_sent_to_token_unchecked(332		owner: &T::CrossAccountId,333		collection_id: CollectionId,334		token_id: TokenId,335	) {336		Self::exec_if_owner_is_valid_nft(owner, |collection, parent_id| {337			collection.nest(parent_id, (collection_id, token_id))338		});339	}340341	/// Unnests `token_id` from `owner`.342	pub fn unnest_if_nested(343		owner: &T::CrossAccountId,344		collection_id: CollectionId,345		token_id: TokenId,346	) {347		Self::exec_if_owner_is_valid_nft(owner, |collection, parent_id| {348			collection.unnest(parent_id, (collection_id, token_id))349		});350	}351352	fn exec_if_owner_is_valid_nft(353		account: &T::CrossAccountId,354		action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId),355	) {356		Self::try_exec_if_owner_is_valid_nft(account, |collection, id| {357			action(collection, id);358			Ok(())359		})360		.unwrap();361	}362363	fn try_exec_if_owner_is_valid_nft(364		account: &T::CrossAccountId,365		action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,366	) -> DispatchResult {367		let account = T::CrossTokenAddressMapping::address_to_token(account);368369		if account.is_none() {370			return Ok(());371		}372373		let account = account.unwrap();374375		let handle = <CollectionHandle<T>>::try_get(account.0);376377		if handle.is_err() {378			return Ok(());379		}380381		let handle = handle.unwrap();382383		let dispatch = T::CollectionDispatch::dispatch(handle);384		let dispatch = dispatch.as_dyn();385386		action(dispatch, account.1)387	}388}