123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354#![cfg_attr(not(feature = "std"), no_std)]5556use frame_support::{dispatch::DispatchResult, fail, pallet_prelude::*};57use pallet_common::{58 dispatch::CollectionDispatch, erc::CrossAccountId, eth::is_collection,59 CommonCollectionOperations,60};61use sp_std::collections::btree_set::BTreeSet;62use up_data_structs::{63 budget::Budget, mapping::TokenAddressMapping, CollectionId, TokenId, TokenOwnerError,64};6566#[cfg(feature = "runtime-benchmarks")]67pub mod benchmarking;68pub mod weights;6970pub use pallet::*;7172pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;7374#[frame_support::pallet]75pub mod pallet {76 use frame_support::{dispatch::GetDispatchInfo, traits::UnfilteredDispatchable, Parameter};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 MultipleOwners,140 141 Token(CollectionId, TokenId),142}143144impl<T: Config> Pallet<T> {145 146 147 148 149 150 151 pub fn find_parent(152 collection: CollectionId,153 token: TokenId,154 ) -> Result<Parent<T::CrossAccountId>, DispatchError> {155 156 let handle = match T::CollectionDispatch::dispatch(collection) {157 Ok(v) => v,158 Err(_) => return Ok(Parent::TokenNotFound),159 };160 let handle = handle.as_dyn();161162 Ok(match handle.token_owner(token) {163 Ok(owner) => match T::CrossTokenAddressMapping::address_to_token(&owner) {164 Some((collection, token)) => Parent::Token(collection, token),165 None => Parent::User(owner),166 },167 Err(TokenOwnerError::MultipleOwners) => Parent::MultipleOwners,168 Err(TokenOwnerError::NotFound) => Parent::TokenNotFound,169 })170 }171172 173 174 175 176 177 pub fn parent_chain(178 mut collection: CollectionId,179 mut token: TokenId,180 ) -> impl Iterator<Item = Result<Parent<T::CrossAccountId>, DispatchError>> {181 let mut finished = false;182 let mut visited = BTreeSet::new();183 visited.insert((collection, token));184 core::iter::from_fn(move || {185 if finished {186 return None;187 }188 let parent = Self::find_parent(collection, token);189 match parent {190 Ok(Parent::Token(new_collection, new_token)) => {191 collection = new_collection;192 token = new_token;193 if !visited.insert((new_collection, new_token)) {194 finished = true;195 return Some(Err(<Error<T>>::OuroborosDetected.into()));196 }197 }198 _ => finished = true,199 }200 Some(parent as Result<_, DispatchError>)201 })202 }203204 205 206 207 208 209 210 211 pub fn find_topmost_owner(212 collection: CollectionId,213 token: TokenId,214 budget: &dyn Budget,215 ) -> Result<Option<T::CrossAccountId>, DispatchError> {216 let owner = Self::parent_chain(collection, token)217 .take_while(|_| budget.consume())218 .find(|p| {219 matches!(220 p,221 Ok(Parent::User(_) | Parent::TokenNotFound | Parent::MultipleOwners)222 )223 })224 .ok_or(<Error<T>>::DepthLimit)??;225226 Ok(match owner {227 Parent::User(v) => Some(v),228 Parent::MultipleOwners => None,229 _ => fail!(<Error<T>>::TokenNotFound),230 })231 }232233 234 235 236 237 238 239 pub fn get_checked_topmost_owner(240 collection: CollectionId,241 token: TokenId,242 for_nest: Option<(CollectionId, TokenId)>,243 budget: &dyn Budget,244 ) -> Result<Option<T::CrossAccountId>, DispatchError> {245 246 if Some((collection, token)) == for_nest {247 return Err(<Error<T>>::OuroborosDetected.into());248 }249250 for parent in Self::parent_chain(collection, token).take_while(|_| budget.consume()) {251 match parent? {252 253 Parent::Token(collection, token) if Some((collection, token)) == for_nest => {254 return Err(<Error<T>>::OuroborosDetected.into())255 }256 257 Parent::User(user) => return Ok(Some(user)),258 Parent::TokenNotFound => return Err(<Error<T>>::TokenNotFound.into()),259 Parent::MultipleOwners => return Ok(None),260 261 Parent::Token(_, _) => {}262 }263 }264265 Err(<Error<T>>::DepthLimit.into())266 }267268 269 270 271 272 273 274 275 pub fn check_indirectly_owned(276 user: T::CrossAccountId,277 collection: CollectionId,278 token: TokenId,279 for_nest: Option<(CollectionId, TokenId)>,280 budget: &dyn Budget,281 ) -> Result<bool, DispatchError> {282 let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {283 Some((collection, token)) => match Self::find_topmost_owner(collection, token, budget)?284 {285 Some(topmost_owner) => topmost_owner,286 None => return Ok(false),287 },288 None => user,289 };290291 Self::get_checked_topmost_owner(collection, token, for_nest, budget).map(|indirect_owner| {292 indirect_owner.map_or(false, |indirect_owner| indirect_owner == target_parent)293 })294 }295296 297 298 299 300 301 302 pub fn check_nesting(303 from: T::CrossAccountId,304 under: &T::CrossAccountId,305 collection_id: CollectionId,306 token_id: TokenId,307 nesting_budget: &dyn Budget,308 ) -> DispatchResult {309 Self::try_exec_if_token(under, |collection, parent_id| {310 collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)311 })312 }313314 315 316 317 318 319 pub fn nest_if_sent_to_token(320 from: T::CrossAccountId,321 under: &T::CrossAccountId,322 collection_id: CollectionId,323 token_id: TokenId,324 nesting_budget: &dyn Budget,325 ) -> DispatchResult {326 Self::try_exec_if_token(under, |collection, parent_id| {327 collection.check_nesting(from, (collection_id, token_id), parent_id, nesting_budget)?;328329 collection.nest(parent_id, (collection_id, token_id));330331 Ok(())332 })333 }334335 336 337 338 pub fn nest_if_sent_to_token_unchecked(339 owner: &T::CrossAccountId,340 collection_id: CollectionId,341 token_id: TokenId,342 ) {343 Self::exec_if_token(owner, |collection, parent_id| {344 collection.nest(parent_id, (collection_id, token_id))345 });346 }347348 349 pub fn unnest_if_nested(350 owner: &T::CrossAccountId,351 collection_id: CollectionId,352 token_id: TokenId,353 ) {354 if let Err(e) = Self::try_exec_if_token(owner, |collection, parent_id| {355 collection.unnest(parent_id, (collection_id, token_id));356 Ok(())357 }) {358 log::warn!("unnest precondition failed: {e:?}")359 }360 }361362 363 364 fn exec_if_token(365 account: &T::CrossAccountId,366 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId),367 ) {368 Self::try_exec_if_token(account, |collection, id| {369 action(collection, id);370 Ok(())371 })372 .unwrap();373 }374375 376 377 fn try_exec_if_token(378 account: &T::CrossAccountId,379 action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,380 ) -> DispatchResult {381 if is_collection(account.as_eth()) {382 fail!(<Error<T>>::CantNestTokenUnderCollection);383 }384 let Some((collection, token)) = T::CrossTokenAddressMapping::address_to_token(account)385 else {386 return Ok(());387 };388389 let dispatch = T::CollectionDispatch::dispatch(collection)?;390 let dispatch = dispatch.as_dyn();391392 action(dispatch, token)393 }394}