12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758#![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 86 OuroborosDetected,87 88 DepthLimit,89 90 BreadthLimit,91 92 TokenNotFound,93 }9495 #[pallet::event]96 pub enum Event<T> {97 98 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 114 115116 117 118 119 120 121 122 123 124 125 126 127 128 }129}130131#[derive(PartialEq)]132pub enum Parent<CrossAccountId> {133 134 User(CrossAccountId),135 136 TokenNotFound,137 138 Token(CollectionId, TokenId),139}140141impl<T: Config> Pallet<T> {142 143 144 145 146 147 148 pub fn find_parent(149 collection: CollectionId,150 token: TokenId,151 ) -> Result<Parent<T::CrossAccountId>, DispatchError> {152 153 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 170 171 172 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 201 202 203 204 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 222 223 224 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 232 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 239 Parent::Token(collection, token) if Some((collection, token)) == for_nest => {240 return Err(<Error<T>>::OuroborosDetected.into())241 }242 243 Parent::User(user) => return Ok(user),244 Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),245 246 Parent::Token(_, _) => {}247 }248 }249250 Err(<Error<T>>::DepthLimit.into())251 }252253 254 255 256 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 271 272 273 274 275 276 277 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 295 296 297 298 299 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 313 314 315 316 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 334 335 336 pub fn nest_if_sent_to_token_unchecked(337 owner: &T::CrossAccountId,338 collection_id: CollectionId,339 token_id: TokenId,340 ) {341 Self::exec_if_owner_is_valid_nft(owner, |collection, parent_id| {342 collection.nest(parent_id, (collection_id, token_id))343 });344 }345346 347 pub fn unnest_if_nested(348 owner: &T::CrossAccountId,349 collection_id: CollectionId,350 token_id: TokenId,351 ) {352 Self::exec_if_owner_is_valid_nft(owner, |collection, parent_id| {353 collection.unnest(parent_id, (collection_id, token_id))354 });355 }356357 fn exec_if_owner_is_valid_nft(358 account: &T::CrossAccountId,359 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId),360 ) {361 Self::try_exec_if_owner_is_valid_nft(account, |collection, id| {362 action(collection, id);363 Ok(())364 })365 .unwrap();366 }367368 fn try_exec_if_owner_is_valid_nft(369 account: &T::CrossAccountId,370 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,371 ) -> DispatchResult {372 let account = T::CrossTokenAddressMapping::address_to_token(account);373374 if account.is_none() {375 return Ok(());376 }377378 let account = account.unwrap();379380 let handle = <CollectionHandle<T>>::try_get(account.0);381382 if handle.is_err() {383 return Ok(());384 }385386 let handle = handle.unwrap();387388 let dispatch = T::CollectionDispatch::dispatch(handle);389 let dispatch = dispatch.as_dyn();390391 action(dispatch, account.1)392 }393}