difftreelog
chore fixed code review request
in: master
1 file changed
pallets/structure/src/lib.rsdiffbeforeafterboth1// 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 /// Get the chain of parents of a token in the nesting hierarchy166 ///167 /// Returns an iterator of addresses of the owning tokens and the owning account,168 /// starting from the immediate parent token, ending with the account.169 /// Returns error if cycle is detected.170 pub fn parent_chain(171 mut collection: CollectionId,172 mut token: TokenId,173 ) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {174 let mut finished = false;175 let mut visited = BTreeSet::new();176 visited.insert((collection, token));177 core::iter::from_fn(move || {178 if finished {179 return None;180 }181 let parent = Self::find_parent(collection, token);182 match parent {183 Ok(Parent::Token(new_collection, new_token)) => {184 collection = new_collection;185 token = new_token;186 if !visited.insert((new_collection, new_token)) {187 finished = true;188 return Some(Err(<Error<T>>::OuroborosDetected.into()));189 }190 }191 _ => finished = true,192 }193 Some(parent as Result<_, DispatchError>)194 })195 }196197 /// Try to dereference address, until finding top level owner198 ///199 /// May return token address if parent token not yet exists200 ///201 /// - `budget`: Limit for searching parents in depth.202 pub fn find_topmost_owner(203 collection: CollectionId,204 token: TokenId,205 budget: &dyn Budget,206 ) -> Result<T::CrossAccountId, DispatchError> {207 let owner = Self::parent_chain(collection, token)208 .take_while(|_| budget.consume())209 .find(|p| matches!(p, Ok(Parent::User(_) | Parent::TokenNotFound)))210 .ok_or(<Error<T>>::DepthLimit)??;211212 Ok(match owner {213 Parent::User(v) => v,214 _ => fail!(<Error<T>>::TokenNotFound),215 })216 }217218 /// Find the topmost parent and check that assigning `for_nest` token as a child for219 /// `token` wouldn't create a cycle.220 ///221 /// - `budget`: Limit for searching parents in depth.222 pub fn get_checked_topmost_owner(223 collection: CollectionId,224 token: TokenId,225 for_nest: Option<(CollectionId, TokenId)>,226 budget: &dyn Budget,227 ) -> Result<T::CrossAccountId, DispatchError> {228 // Tried to nest token in itself229 if Some((collection, token)) == for_nest {230 return Err(<Error<T>>::OuroborosDetected.into());231 }232233 for parent in Self::parent_chain(collection, token).take_while(|_| budget.consume()) {234 match parent? {235 // Tried to nest token in chain, which has this token as one of parents236 Parent::Token(collection, token) if Some((collection, token)) == for_nest => {237 return Err(<Error<T>>::OuroborosDetected.into())238 }239 // Token is owned by other user240 Parent::User(user) => return Ok(user),241 Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),242 // Continue parent chain243 Parent::Token(_, _) => {}244 }245 }246247 Err(<Error<T>>::DepthLimit.into())248 }249250 /// Burn token and all of it's nested tokens251 ///252 /// - `self_budget`: Limit for searching children in depth.253 /// - `breadth_budget`: Limit of breadth of searching children.254 pub fn burn_item_recursively(255 from: T::CrossAccountId,256 collection: CollectionId,257 token: TokenId,258 self_budget: &dyn Budget,259 breadth_budget: &dyn Budget,260 ) -> DispatchResultWithPostInfo {261 let handle = <CollectionHandle<T>>::try_get(collection)?;262 let dispatch = T::CollectionDispatch::dispatch(handle);263 let dispatch = dispatch.as_dyn();264 dispatch.burn_item_recursively(from.clone(), token, self_budget, breadth_budget)265 }266267 /// Check if `token` indirectly owned by `user`268 ///269 /// Returns `true` if `user` is `token`'s owner. Or If token is provided as `user` then270 /// check that `user` and `token` have same owner.271 /// Checks that assigning `for_nest` token as a child for `token` wouldn't create a cycle.272 ///273 /// - `budget`: Limit for searching parents in depth.274 pub fn check_indirectly_owned(275 user: T::CrossAccountId,276 collection: CollectionId,277 token: TokenId,278 for_nest: Option<(CollectionId, TokenId)>,279 budget: &dyn Budget,280 ) -> Result<bool, DispatchError> {281 let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {282 Some((collection, token)) => Self::find_topmost_owner(collection, token, budget)?,283 None => user,284 };285286 Self::get_checked_topmost_owner(collection, token, for_nest, budget)287 .map(|indirect_owner| indirect_owner == target_parent)288 }289290 /// Checks that `under` is valid token and that `token_id` could be nested under it291 /// and that `from` is `under`'s owner292 ///293 /// Returns OK if `under` is not a token294 ///295 /// - `nesting_budget`: Limit for searching parents in depth.296 pub fn check_nesting(297 from: T::CrossAccountId,298 under: &T::CrossAccountId,299 collection_id: CollectionId,300 token_id: TokenId,301 nesting_budget: &dyn Budget,302 ) -> DispatchResult {303 Self::try_exec_if_owner_is_valid_nft(under, |collection, parent_id| {304 collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)305 })306 }307308 /// Nests `token_id` under `under` token309 ///310 /// Returns OK if `under` is not a token. Checks that nesting is possible.311 ///312 /// - `nesting_budget`: Limit for searching parents in depth.313 pub fn nest_if_sent_to_token(314 from: T::CrossAccountId,315 under: &T::CrossAccountId,316 collection_id: CollectionId,317 token_id: TokenId,318 nesting_budget: &dyn Budget,319 ) -> DispatchResult {320 Self::try_exec_if_owner_is_valid_nft(under, |collection, parent_id| {321 collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)?;322323 collection.nest(parent_id, (collection_id, token_id));324325 Ok(())326 })327 }328329 /// Nests `token_id` under `owner` token330 ///331 /// Caller should check that nesting wouldn't cause recursion in nesting332 pub fn nest_if_sent_to_token_unchecked(333 owner: &T::CrossAccountId,334 collection_id: CollectionId,335 token_id: TokenId,336 ) {337 Self::exec_if_owner_is_valid_nft(owner, |collection, parent_id| {338 collection.nest(parent_id, (collection_id, token_id))339 });340 }341342 /// Unnests `token_id` from `owner`.343 pub fn unnest_if_nested(344 owner: &T::CrossAccountId,345 collection_id: CollectionId,346 token_id: TokenId,347 ) {348 Self::exec_if_owner_is_valid_nft(owner, |collection, parent_id| {349 collection.unnest(parent_id, (collection_id, token_id))350 });351 }352353 fn exec_if_owner_is_valid_nft(354 account: &T::CrossAccountId,355 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId),356 ) {357 Self::try_exec_if_owner_is_valid_nft(account, |collection, id| {358 action(collection, id);359 Ok(())360 })361 .unwrap();362 }363364 fn try_exec_if_owner_is_valid_nft(365 account: &T::CrossAccountId,366 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,367 ) -> DispatchResult {368 let account = T::CrossTokenAddressMapping::address_to_token(account);369370 if account.is_none() {371 return Ok(());372 }373374 let account = account.unwrap();375376 let handle = <CollectionHandle<T>>::try_get(account.0);377378 if handle.is_err() {379 return Ok(());380 }381382 let handle = handle.unwrap();383384 let dispatch = T::CollectionDispatch::dispatch(handle);385 let dispatch = dispatch.as_dyn();386387 action(dispatch, account.1)388 }389}