difftreelog
doc: added documentation for structure pallet
in: master
2 files changed
pallets/structure/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/structure/src/benchmarking.rs
+++ b/pallets/structure/src/benchmarking.rs
@@ -1,3 +1,19 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
use super::*;
use frame_benchmarking::{benchmarks, account};
pallets/structure/src/lib.rsdiffbeforeafterboth1#![cfg_attr(not(feature = "std"), no_std)]23use pallet_common::CommonCollectionOperations;4use sp_std::collections::btree_set::BTreeSet;56use frame_support::dispatch::{DispatchError, DispatchResult, DispatchResultWithPostInfo};7use frame_support::fail;8pub use pallet::*;9use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};10use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};1112#[cfg(feature = "runtime-benchmarks")]13pub mod benchmarking;14pub mod weights;1516pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;1718#[frame_support::pallet]19pub mod pallet {20 use frame_support::Parameter;21 use frame_support::dispatch::{GetDispatchInfo, UnfilteredDispatchable};22 use frame_support::pallet_prelude::*;2324 use super::*;2526 #[pallet::error]27 pub enum Error<T> {28 /// While searched for owner, got already checked account29 OuroborosDetected,30 /// While searched for owner, encountered depth limit31 DepthLimit,32 /// While iterating over children, encountered breadth limit33 BreadthLimit,34 /// While searched for owner, found token owner by not-yet-existing token35 TokenNotFound,36 }3738 #[pallet::event]39 pub enum Event<T> {40 /// Executed call on behalf of token41 Executed(DispatchResult),42 }4344 #[pallet::config]45 pub trait Config: frame_system::Config + pallet_common::Config {46 type WeightInfo: weights::WeightInfo;47 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;48 type Call: Parameter + UnfilteredDispatchable<Origin = Self::Origin> + GetDispatchInfo;49 }5051 #[pallet::pallet]52 pub struct Pallet<T>(_);5354 #[pallet::call]55 impl<T: Config> Pallet<T> {56 // #[pallet::weight({57 // let dispatch_info = call.get_dispatch_info();5859 // (60 // dispatch_info.weight61 // // Cost of dereferencing parent62 // .saturating_add(T::DbWeight::get().reads(2 * *max_depth as Weight))63 // .saturating_add(4000 * *max_depth as Weight),64 // dispatch_info.class)65 // })]66 // pub fn execute(67 // origin: OriginFor<T>,68 // call: Box<<T as Config>::Call>,69 // max_depth: u32,70 // ) -> DispatchResult {71 }72}7374#[derive(PartialEq)]75pub enum Parent<CrossAccountId> {76 /// Token owned by normal account77 User(CrossAccountId),78 /// Passed token not found79 TokenNotFound,80 /// Token owner is another token (target token still may not exist)81 Token(CollectionId, TokenId),82}8384impl<T: Config> Pallet<T> {85 pub fn find_parent(86 collection: CollectionId,87 token: TokenId,88 ) -> Result<Parent<T::CrossAccountId>, DispatchError> {89 // TODO: Reduce cost by not reading collection config90 let handle = match CollectionHandle::try_get(collection) {91 Ok(v) => v,92 Err(_) => return Ok(Parent::TokenNotFound),93 };94 let handle = T::CollectionDispatch::dispatch(handle);95 let handle = handle.as_dyn();9697 Ok(match handle.token_owner(token) {98 Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {99 Some((collection, token)) => Parent::Token(collection, token),100 None => Parent::User(owner),101 },102 None => Parent::TokenNotFound,103 })104 }105106 pub fn parent_chain(107 mut collection: CollectionId,108 mut token: TokenId,109 ) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {110 let mut finished = false;111 let mut visited = BTreeSet::new();112 visited.insert((collection, token));113 core::iter::from_fn(move || {114 if finished {115 return None;116 }117 let parent = Self::find_parent(collection, token);118 match parent {119 Ok(Parent::Token(new_collection, new_token)) => {120 collection = new_collection;121 token = new_token;122 if !visited.insert((new_collection, new_token)) {123 finished = true;124 return Some(Err(<Error<T>>::OuroborosDetected.into()));125 }126 }127 _ => finished = true,128 }129 Some(parent as Result<_, DispatchError>)130 })131 }132133 /// Try to dereference address, until finding top level owner134 ///135 /// May return token address if parent token not yet exists136 pub fn find_topmost_owner(137 collection: CollectionId,138 token: TokenId,139 budget: &dyn Budget,140 ) -> Result<T::CrossAccountId, DispatchError> {141 let owner = Self::parent_chain(collection, token)142 .take_while(|_| budget.consume())143 .find(|p| matches!(p, Ok(Parent::User(_) | Parent::TokenNotFound)))144 .ok_or(<Error<T>>::DepthLimit)??;145146 Ok(match owner {147 Parent::User(v) => v,148 _ => fail!(<Error<T>>::TokenNotFound),149 })150 }151152 pub fn get_checked_topmost_owner(153 collection: CollectionId,154 token: TokenId,155 for_nest: Option<(CollectionId, TokenId)>,156 budget: &dyn Budget,157 ) -> Result<T::CrossAccountId, DispatchError> {158 // Tried to nest token in itself159 if Some((collection, token)) == for_nest {160 return Err(<Error<T>>::OuroborosDetected.into());161 }162163 for parent in Self::parent_chain(collection, token).take_while(|_| budget.consume()) {164 match parent? {165 // Tried to nest token in chain, which has this token as one of parents166 Parent::Token(collection, token) if Some((collection, token)) == for_nest => {167 return Err(<Error<T>>::OuroborosDetected.into())168 }169 // Token is owned by other user170 Parent::User(user) => return Ok(user),171 Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),172 // Continue parent chain173 Parent::Token(_, _) => {}174 }175 }176177 Err(<Error<T>>::DepthLimit.into())178 }179180 pub fn burn_item_recursively(181 from: T::CrossAccountId,182 collection: CollectionId,183 token: TokenId,184 self_budget: &dyn Budget,185 breadth_budget: &dyn Budget,186 ) -> DispatchResultWithPostInfo {187 let handle = <CollectionHandle<T>>::try_get(collection)?;188 let dispatch = T::CollectionDispatch::dispatch(handle);189 let dispatch = dispatch.as_dyn();190 dispatch.burn_item_recursively(from.clone(), token, self_budget, breadth_budget)191 }192193 /// Check if token indirectly owned by specified user194 pub fn check_indirectly_owned(195 user: T::CrossAccountId,196 collection: CollectionId,197 token: TokenId,198 for_nest: Option<(CollectionId, TokenId)>,199 budget: &dyn Budget,200 ) -> Result<bool, DispatchError> {201 let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {202 Some((collection, token)) => Self::find_topmost_owner(collection, token, budget)?,203 None => user,204 };205206 Self::get_checked_topmost_owner(collection, token, for_nest, budget)207 .map(|indirect_owner| indirect_owner == target_parent)208 }209210 pub fn check_nesting(211 from: T::CrossAccountId,212 under: &T::CrossAccountId,213 collection_id: CollectionId,214 token_id: TokenId,215 nesting_budget: &dyn Budget,216 ) -> DispatchResult {217 Self::try_exec_if_owner_is_valid_nft(under, |collection, parent_id| {218 collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)219 })220 }221222 pub fn nest_if_sent_to_token(223 from: T::CrossAccountId,224 under: &T::CrossAccountId,225 collection_id: CollectionId,226 token_id: TokenId,227 nesting_budget: &dyn Budget,228 ) -> DispatchResult {229 Self::try_exec_if_owner_is_valid_nft(under, |collection, parent_id| {230 collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)?;231232 collection.nest(parent_id, (collection_id, token_id));233234 Ok(())235 })236 }237238 pub fn nest_if_sent_to_token_unchecked(239 owner: &T::CrossAccountId,240 collection_id: CollectionId,241 token_id: TokenId,242 ) {243 Self::exec_if_owner_is_valid_nft(owner, |collection, parent_id| {244 collection.nest(parent_id, (collection_id, token_id))245 });246 }247248 pub fn unnest_if_nested(249 owner: &T::CrossAccountId,250 collection_id: CollectionId,251 token_id: TokenId,252 ) {253 Self::exec_if_owner_is_valid_nft(owner, |collection, parent_id| {254 collection.unnest(parent_id, (collection_id, token_id))255 });256 }257258 fn exec_if_owner_is_valid_nft(259 account: &T::CrossAccountId,260 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId),261 ) {262 Self::try_exec_if_owner_is_valid_nft(account, |collection, id| {263 action(collection, id);264 Ok(())265 })266 .unwrap();267 }268269 fn try_exec_if_owner_is_valid_nft(270 account: &T::CrossAccountId,271 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,272 ) -> DispatchResult {273 let account = T::CrossTokenAddressMapping::address_to_token(account);274275 if account.is_none() {276 return Ok(());277 }278279 let account = account.unwrap();280281 let handle = <CollectionHandle<T>>::try_get(account.0);282283 if handle.is_err() {284 return Ok(());285 }286287 let handle = handle.unwrap();288289 let dispatch = T::CollectionDispatch::dispatch(handle);290 let dispatch = dispatch.as_dyn();291292 action(dispatch, account.1)293 }294}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//! ### Dispatchable 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 token53//!54//! ## Assumptions55//!56//! * Total issued balanced of all accounts should be less than `Config::Balance::max_value()`.5758#![cfg_attr(not(feature = "std"), no_std)]5960use pallet_common::CommonCollectionOperations;61use sp_std::collections::btree_set::BTreeSet;6263use frame_support::dispatch::{DispatchError, DispatchResult, DispatchResultWithPostInfo};64use frame_support::fail;65pub use pallet::*;66use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};67use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};6869#[cfg(feature = "runtime-benchmarks")]70pub mod benchmarking;71pub mod weights;7273pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;7475#[frame_support::pallet]76pub mod pallet {77 use frame_support::Parameter;78 use frame_support::dispatch::{GetDispatchInfo, UnfilteredDispatchable};79 use frame_support::pallet_prelude::*;8081 use super::*;8283 #[pallet::error]84 pub enum Error<T> {85 /// While searched for owner, got already checked account86 OuroborosDetected,87 /// While searched for owner, encountered depth limit88 DepthLimit,89 /// While iterating over children, encountered breadth limit90 BreadthLimit,91 /// While searched for owner, found token owner by not-yet-existing token92 TokenNotFound,93 }9495 #[pallet::event]96 pub enum Event<T> {97 /// Executed call on behalf of token98 Executed(DispatchResult),99 }100101 #[pallet::config]102 pub trait Config: frame_system::Config + pallet_common::Config {103 type WeightInfo: weights::WeightInfo;104 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;105 type Call: Parameter + UnfilteredDispatchable<Origin = Self::Origin> + GetDispatchInfo;106 }107108 #[pallet::pallet]109 pub struct Pallet<T>(_);110111 #[pallet::call]112 impl<T: Config> Pallet<T> {113 // #[pallet::weight({114 // let dispatch_info = call.get_dispatch_info();115116 // (117 // dispatch_info.weight118 // // Cost of dereferencing parent119 // .saturating_add(T::DbWeight::get().reads(2 * *max_depth as Weight))120 // .saturating_add(4000 * *max_depth as Weight),121 // dispatch_info.class)122 // })]123 // pub fn execute(124 // origin: OriginFor<T>,125 // call: Box<<T as Config>::Call>,126 // max_depth: u32,127 // ) -> DispatchResult {128 }129}130131#[derive(PartialEq)]132pub enum Parent<CrossAccountId> {133 /// Token owned by normal account134 User(CrossAccountId),135 /// Passed token not found136 TokenNotFound,137 /// Token owner is another token (target token still may not exist)138 Token(CollectionId, TokenId),139}140141impl<T: Config> Pallet<T> {142 /// Find account owning the `token` or a token that the `token` is nested in.143 ///144 /// Returns the enum that have three variants:145 /// - [`User`](crate::Parent<T>::User): Contains account.146 /// - [`Token`](crate::Parent<T>::Token): Contains token id and collection id.147 /// - [`TokenNotFound`](crate::Parent<T>::TokenNotFound): Indicates that parent was not found148 pub fn find_parent(149 collection: CollectionId,150 token: TokenId,151 ) -> Result<Parent<T::CrossAccountId>, DispatchError> {152 // TODO: Reduce cost by not reading collection config153 let handle = match CollectionHandle::try_get(collection) {154 Ok(v) => v,155 Err(_) => return Ok(Parent::TokenNotFound),156 };157 let handle = T::CollectionDispatch::dispatch(handle);158 let handle = handle.as_dyn();159160 Ok(match handle.token_owner(token) {161 Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {162 Some((collection, token)) => Parent::Token(collection, token),163 None => Parent::User(owner),164 },165 None => Parent::TokenNotFound,166 })167 }168169 /// Find chain of parents of current token170 ///171 /// Returns the parent of the current token, than the parent of the parent and so on until token without a parent172 /// is returned. Returns error if cycle is detected.173 pub fn parent_chain(174 mut collection: CollectionId,175 mut token: TokenId,176 ) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {177 let mut finished = false;178 let mut visited = BTreeSet::new();179 visited.insert((collection, token));180 core::iter::from_fn(move || {181 if finished {182 return None;183 }184 let parent = Self::find_parent(collection, token);185 match parent {186 Ok(Parent::Token(new_collection, new_token)) => {187 collection = new_collection;188 token = new_token;189 if !visited.insert((new_collection, new_token)) {190 finished = true;191 return Some(Err(<Error<T>>::OuroborosDetected.into()));192 }193 }194 _ => finished = true,195 }196 Some(parent as Result<_, DispatchError>)197 })198 }199200 /// Try to dereference address, until finding top level owner201 ///202 /// May return token address if parent token not yet exists203 ///204 /// - `budget`: Limit for searching parents in depth.205 pub fn find_topmost_owner(206 collection: CollectionId,207 token: TokenId,208 budget: &dyn Budget,209 ) -> Result<T::CrossAccountId, DispatchError> {210 let owner = Self::parent_chain(collection, token)211 .take_while(|_| budget.consume())212 .find(|p| matches!(p, Ok(Parent::User(_) | Parent::TokenNotFound)))213 .ok_or(<Error<T>>::DepthLimit)??;214215 Ok(match owner {216 Parent::User(v) => v,217 _ => fail!(<Error<T>>::TokenNotFound),218 })219 }220221 /// Find the topmost parent and check that assigning `for_nest` token as a parent for222 /// any token in the parents chain wouldn't create a cycle.223 ///224 /// - `budget`: Limit for searching parents in depth.225 pub fn get_checked_topmost_owner(226 collection: CollectionId,227 token: TokenId,228 for_nest: Option<(CollectionId, TokenId)>,229 budget: &dyn Budget,230 ) -> Result<T::CrossAccountId, DispatchError> {231 // Tried to nest token in itself232 if Some((collection, token)) == for_nest {233 return Err(<Error<T>>::OuroborosDetected.into());234 }235236 for parent in Self::parent_chain(collection, token).take_while(|_| budget.consume()) {237 match parent? {238 // Tried to nest token in chain, which has this token as one of parents239 Parent::Token(collection, token) if Some((collection, token)) == for_nest => {240 return Err(<Error<T>>::OuroborosDetected.into())241 }242 // Token is owned by other user243 Parent::User(user) => return Ok(user),244 Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),245 // Continue parent chain246 Parent::Token(_, _) => {}247 }248 }249250 Err(<Error<T>>::DepthLimit.into())251 }252253 /// Burn token and all of it's nested tokens254 ///255 /// - `self_budget`: Limit for searching children in depth.256 /// - `breadth_budget`: Limit of breadth of searching children.257 pub fn burn_item_recursively(258 from: T::CrossAccountId,259 collection: CollectionId,260 token: TokenId,261 self_budget: &dyn Budget,262 breadth_budget: &dyn Budget,263 ) -> DispatchResultWithPostInfo {264 let handle = <CollectionHandle<T>>::try_get(collection)?;265 let dispatch = T::CollectionDispatch::dispatch(handle);266 let dispatch = dispatch.as_dyn();267 dispatch.burn_item_recursively(from.clone(), token, self_budget, breadth_budget)268 }269270 /// Check if `token` indirectly owned by `user`271 ///272 /// Returns `true` if `user` is `token`'s owner. Or If token is provided as `user` then273 /// check that `user` and `token` have same owner.274 /// Checks that assigning `for_nest` token as a parent for any token in the `token`'s275 /// parents chain wouldn't create a cycle.276 ///277 /// - `budget`: Limit for searching parents in depth.278 pub fn check_indirectly_owned(279 user: T::CrossAccountId,280 collection: CollectionId,281 token: TokenId,282 for_nest: Option<(CollectionId, TokenId)>,283 budget: &dyn Budget,284 ) -> Result<bool, DispatchError> {285 let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {286 Some((collection, token)) => Self::find_topmost_owner(collection, token, budget)?,287 None => user,288 };289290 Self::get_checked_topmost_owner(collection, token, for_nest, budget)291 .map(|indirect_owner| indirect_owner == target_parent)292 }293294 /// Checks that `under` is valid token and that `token_id` could be nested under it295 /// and that `from` is `under`'s owner296 ///297 /// Returns OK if `under` is not a token298 ///299 /// - `nesting_budget`: Limit for searching parents in depth.300 pub fn check_nesting(301 from: T::CrossAccountId,302 under: &T::CrossAccountId,303 collection_id: CollectionId,304 token_id: TokenId,305 nesting_budget: &dyn Budget,306 ) -> DispatchResult {307 Self::try_exec_if_owner_is_valid_nft(under, |collection, parent_id| {308 collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)309 })310 }311312 /// Nests `token_id` under `under` token313 ///314 /// Returns OK if `under` is not a token. Checks that nesting is possible.315 ///316 /// - `nesting_budget`: Limit for searching parents in depth.317 pub fn nest_if_sent_to_token(318 from: T::CrossAccountId,319 under: &T::CrossAccountId,320 collection_id: CollectionId,321 token_id: TokenId,322 nesting_budget: &dyn Budget,323 ) -> DispatchResult {324 Self::try_exec_if_owner_is_valid_nft(under, |collection, parent_id| {325 collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)?;326327 collection.nest(parent_id, (collection_id, token_id));328329 Ok(())330 })331 }332333 /// Nests `token_id` under `owner` token334 pub fn nest_if_sent_to_token_unchecked(335 owner: &T::CrossAccountId,336 collection_id: CollectionId,337 token_id: TokenId,338 ) {339 Self::exec_if_owner_is_valid_nft(owner, |collection, parent_id| {340 collection.nest(parent_id, (collection_id, token_id))341 });342 }343344 /// Unnests `token_id` from `owner`.345 pub fn unnest_if_nested(346 owner: &T::CrossAccountId,347 collection_id: CollectionId,348 token_id: TokenId,349 ) {350 Self::exec_if_owner_is_valid_nft(owner, |collection, parent_id| {351 collection.unnest(parent_id, (collection_id, token_id))352 });353 }354355 fn exec_if_owner_is_valid_nft(356 account: &T::CrossAccountId,357 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId),358 ) {359 Self::try_exec_if_owner_is_valid_nft(account, |collection, id| {360 action(collection, id);361 Ok(())362 })363 .unwrap();364 }365366 fn try_exec_if_owner_is_valid_nft(367 account: &T::CrossAccountId,368 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,369 ) -> DispatchResult {370 let account = T::CrossTokenAddressMapping::address_to_token(account);371372 if account.is_none() {373 return Ok(());374 }375376 let account = account.unwrap();377378 let handle = <CollectionHandle<T>>::try_get(account.0);379380 if handle.is_err() {381 return Ok(());382 }383384 let handle = handle.unwrap();385386 let dispatch = T::CollectionDispatch::dispatch(handle);387 let dispatch = dispatch.as_dyn();388389 action(dispatch, account.1)390 }391}