123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354#![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 82 OuroborosDetected,83 84 DepthLimit,85 86 BreadthLimit,87 88 TokenNotFound,89 }9091 #[pallet::event]92 pub enum Event<T> {93 94 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 110 111112 113 114 115 116 117 118 119 120 121 122 123 124 }125}126127#[derive(PartialEq)]128pub enum Parent<CrossAccountId> {129 130 User(CrossAccountId),131 132 TokenNotFound,133 134 Token(CollectionId, TokenId),135}136137impl<T: Config> Pallet<T> {138 139 140 141 142 143 144 pub fn find_parent(145 collection: CollectionId,146 token: TokenId,147 ) -> Result<Parent<T::CrossAccountId>, DispatchError> {148 149 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 166 167 168 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 197 198 199 200 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 218 219 220 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 228 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 235 Parent::Token(collection, token) if Some((collection, token)) == for_nest => {236 return Err(<Error<T>>::OuroborosDetected.into())237 }238 239 Parent::User(user) => return Ok(user),240 Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),241 242 Parent::Token(_, _) => {}243 }244 }245246 Err(<Error<T>>::DepthLimit.into())247 }248249 250 251 252 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 267 268 269 270 271 272 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 290 291 292 293 294 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 308 309 310 311 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 329 330 331 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 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}