123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354#![cfg_attr(not(feature = "std"), no_std)]5556use pallet_common::CommonCollectionOperations;57use pallet_common::{erc::CrossAccountId, eth::is_collection};58use sp_std::collections::btree_set::BTreeSet;5960use frame_support::dispatch::{DispatchError, DispatchResult, DispatchResultWithPostInfo};61use frame_support::fail;62pub use pallet::*;63use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};64use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};6566#[cfg(feature = "runtime-benchmarks")]67pub mod benchmarking;68pub mod weights;6970pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;7172#[frame_support::pallet]73pub mod pallet {74 use frame_support::Parameter;75 use frame_support::dispatch::{GetDispatchInfo, UnfilteredDispatchable};76 use frame_support::pallet_prelude::*;7778 use super::*;7980 #[pallet::error]81 pub enum Error<T> {82 83 OuroborosDetected,84 85 DepthLimit,86 87 BreadthLimit,88 89 TokenNotFound,90 91 CantNestTokenUnderCollection,92 }9394 #[pallet::event]95 pub enum Event<T> {96 97 Executed(DispatchResult),98 }99100 #[pallet::config]101 pub trait Config: frame_system::Config + pallet_common::Config {102 type WeightInfo: weights::WeightInfo;103 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;104 type RuntimeCall: Parameter105 + UnfilteredDispatchable<RuntimeOrigin = Self::RuntimeOrigin>106 + GetDispatchInfo;107 }108109 #[pallet::pallet]110 pub struct Pallet<T>(_);111112 #[pallet::call]113 impl<T: Config> Pallet<T> {114 115 116117 118 119 120 121 122 123 124 125 126 127 128 129 }130}131132#[derive(PartialEq)]133pub enum Parent<CrossAccountId> {134 135 User(CrossAccountId),136 137 TokenNotFound,138 139 Token(CollectionId, TokenId),140}141142impl<T: Config> Pallet<T> {143 144 145 146 147 148 149 pub fn find_parent(150 collection: CollectionId,151 token: TokenId,152 ) -> Result<Parent<T::CrossAccountId>, DispatchError> {153 154 let handle = match CollectionHandle::try_get(collection) {155 Ok(v) => v,156 Err(_) => return Ok(Parent::TokenNotFound),157 };158 let handle = T::CollectionDispatch::dispatch(handle);159 let handle = handle.as_dyn();160161 Ok(match handle.token_owner(token) {162 Some(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {163 Some((collection, token)) => Parent::Token(collection, token),164 None => Parent::User(owner),165 },166 None => Parent::TokenNotFound,167 })168 }169170 171 172 173 174 175 pub fn parent_chain(176 mut collection: CollectionId,177 mut token: TokenId,178 ) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {179 let mut finished = false;180 let mut visited = BTreeSet::new();181 visited.insert((collection, token));182 core::iter::from_fn(move || {183 if finished {184 return None;185 }186 let parent = Self::find_parent(collection, token);187 match parent {188 Ok(Parent::Token(new_collection, new_token)) => {189 collection = new_collection;190 token = new_token;191 if !visited.insert((new_collection, new_token)) {192 finished = true;193 return Some(Err(<Error<T>>::OuroborosDetected.into()));194 }195 }196 _ => finished = true,197 }198 Some(parent as Result<_, DispatchError>)199 })200 }201202 203 204 205 206 207 pub fn find_topmost_owner(208 collection: CollectionId,209 token: TokenId,210 budget: &dyn Budget,211 ) -> Result<T::CrossAccountId, DispatchError> {212 let owner = Self::parent_chain(collection, token)213 .take_while(|_| budget.consume())214 .find(|p| matches!(p, Ok(Parent::User(_) | Parent::TokenNotFound)))215 .ok_or(<Error<T>>::DepthLimit)??;216217 Ok(match owner {218 Parent::User(v) => v,219 _ => fail!(<Error<T>>::TokenNotFound),220 })221 }222223 224 225 226 227 pub fn get_checked_topmost_owner(228 collection: CollectionId,229 token: TokenId,230 for_nest: Option<(CollectionId, TokenId)>,231 budget: &dyn Budget,232 ) -> Result<T::CrossAccountId, DispatchError> {233 234 if Some((collection, token)) == for_nest {235 return Err(<Error<T>>::OuroborosDetected.into());236 }237238 for parent in Self::parent_chain(collection, token).take_while(|_| budget.consume()) {239 match parent? {240 241 Parent::Token(collection, token) if Some((collection, token)) == for_nest => {242 return Err(<Error<T>>::OuroborosDetected.into())243 }244 245 Parent::User(user) => return Ok(user),246 Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),247 248 Parent::Token(_, _) => {}249 }250 }251252 Err(<Error<T>>::DepthLimit.into())253 }254255 256 257 258 259 pub fn burn_item_recursively(260 from: T::CrossAccountId,261 collection: CollectionId,262 token: TokenId,263 self_budget: &dyn Budget,264 breadth_budget: &dyn Budget,265 ) -> DispatchResultWithPostInfo {266 let handle = <CollectionHandle<T>>::try_get(collection)?;267 let dispatch = T::CollectionDispatch::dispatch(handle);268 let dispatch = dispatch.as_dyn();269 dispatch.burn_item_recursively(from.clone(), token, self_budget, breadth_budget)270 }271272 273 274 275 276 277 278 279 pub fn check_indirectly_owned(280 user: T::CrossAccountId,281 collection: CollectionId,282 token: TokenId,283 for_nest: Option<(CollectionId, TokenId)>,284 budget: &dyn Budget,285 ) -> Result<bool, DispatchError> {286 let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {287 Some((collection, token)) => Self::find_topmost_owner(collection, token, budget)?,288 None => user,289 };290291 Self::get_checked_topmost_owner(collection, token, for_nest, budget)292 .map(|indirect_owner| indirect_owner == target_parent)293 }294295 296 297 298 299 300 301 pub fn check_nesting(302 from: T::CrossAccountId,303 under: &T::CrossAccountId,304 collection_id: CollectionId,305 token_id: TokenId,306 nesting_budget: &dyn Budget,307 ) -> DispatchResult {308 Self::try_exec_if_token(under, |collection, parent_id| {309 collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)310 })311 }312313 314 315 316 317 318 pub fn nest_if_sent_to_token(319 from: T::CrossAccountId,320 under: &T::CrossAccountId,321 collection_id: CollectionId,322 token_id: TokenId,323 nesting_budget: &dyn Budget,324 ) -> DispatchResult {325 Self::try_exec_if_token(under, |collection, parent_id| {326 collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)?;327328 collection.nest(parent_id, (collection_id, token_id));329330 Ok(())331 })332 }333334 335 336 337 pub fn nest_if_sent_to_token_unchecked(338 owner: &T::CrossAccountId,339 collection_id: CollectionId,340 token_id: TokenId,341 ) {342 Self::exec_if_token(owner, |collection, parent_id| {343 collection.nest(parent_id, (collection_id, token_id))344 });345 }346347 348 pub fn unnest_if_nested(349 owner: &T::CrossAccountId,350 collection_id: CollectionId,351 token_id: TokenId,352 ) {353 if let Err(e) = Self::try_exec_if_token(owner, |collection, parent_id| {354 collection.unnest(parent_id, (collection_id, token_id));355 Ok(())356 }) {357 log::warn!("unnest precondition failed: {e:?}")358 }359 }360361 362 363 fn exec_if_token(364 account: &T::CrossAccountId,365 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId),366 ) {367 Self::try_exec_if_token(account, |collection, id| {368 action(collection, id);369 Ok(())370 })371 .unwrap();372 }373374 375 376 fn try_exec_if_token(377 account: &T::CrossAccountId,378 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,379 ) -> DispatchResult {380 if is_collection(&account.as_eth()) {381 fail!(<Error<T>>::CantNestTokenUnderCollection);382 }383 let Some((collection, token)) = T::CrossTokenAddressMapping::address_to_token(account) else {384 return Ok(())385 };386387 let handle = <CollectionHandle<T>>::try_get(collection)?;388389 let dispatch = T::CollectionDispatch::dispatch(handle);390 let dispatch = dispatch.as_dyn();391392 action(dispatch, token)393 }394}