1234567891011121314151617use core::marker::PhantomData;1819use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight};20use pallet_common::{21 weights::WeightInfo as _, with_weight, write_token_properties_total_weight,22 CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions,23};24use pallet_structure::Pallet as PalletStructure;25use sp_runtime::DispatchError;26use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};27use up_data_structs::{28 budget::Budget, CollectionId, CreateItemExData, CreateRefungibleExMultipleOwners,29 CreateRefungibleExSingleOwner, Property, PropertyKey, PropertyKeyPermission, PropertyValue,30 TokenId, TokenOwnerError,31};3233use crate::{34 weights::WeightInfo, AccountBalance, Allowance, Balance, Config, CreateItemData, Error, Owned,35 Pallet, RefungibleHandle, SelfWeightOf, TokenProperties, TokensMinted, TotalSupply,36};3738macro_rules! max_weight_of {39 ($($method:ident ($($args:tt)*)),*) => {40 Weight::zero()41 $(42 .max(<SelfWeightOf<T>>::$method($($args)*))43 )*44 };45}4647pub struct CommonWeights<T: Config>(PhantomData<T>);48impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {49 fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {50 mint_with_props_weight::<T>(51 <SelfWeightOf<T>>::create_multiple_items(data.len() as u32),52 data.iter().map(|data| match data {53 up_data_structs::CreateItemData::ReFungible(rft_data) => {54 rft_data.properties.len() as u3255 }56 _ => 0,57 }),58 )59 }6061 fn create_multiple_items_ex(call: &CreateItemExData<T::CrossAccountId>) -> Weight {62 match call {63 CreateItemExData::RefungibleMultipleOwners(i) => mint_with_props_weight::<T>(64 <SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(i.users.len() as u32),65 [i.properties.len() as u32].into_iter(),66 ),67 CreateItemExData::RefungibleMultipleItems(i) => mint_with_props_weight::<T>(68 <SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(i.len() as u32),69 i.iter().map(|d| d.properties.len() as u32),70 ),71 _ => Weight::zero(),72 }73 }7475 fn burn_item() -> Weight {76 max_weight_of!(burn_item_partial(), burn_item_fully())77 }7879 fn set_collection_properties(amount: u32) -> Weight {80 <pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)81 }8283 fn set_token_properties(amount: u32) -> Weight {84 write_token_properties_total_weight::<T, _>([amount].into_iter(), |amount| {85 <SelfWeightOf<T>>::load_token_properties()86 + <SelfWeightOf<T>>::write_token_properties(amount)87 })88 }8990 fn set_token_property_permissions(amount: u32) -> Weight {91 <SelfWeightOf<T>>::set_token_property_permissions(amount)92 }9394 fn transfer() -> Weight {95 max_weight_of!(96 transfer_normal(),97 transfer_creating(),98 transfer_removing(),99 transfer_creating_removing()100 )101 }102103 fn approve() -> Weight {104 <SelfWeightOf<T>>::approve()105 }106107 fn approve_from() -> Weight {108 <SelfWeightOf<T>>::approve_from()109 }110111 fn transfer_from() -> Weight {112 max_weight_of!(113 transfer_from_normal(),114 transfer_from_creating(),115 transfer_from_removing(),116 transfer_from_creating_removing()117 )118 }119120 fn burn_from() -> Weight {121 <SelfWeightOf<T>>::burn_from()122 }123124 fn set_allowance_for_all() -> Weight {125 <SelfWeightOf<T>>::set_allowance_for_all()126 }127128 fn force_repair_item() -> Weight {129 <SelfWeightOf<T>>::repair_item()130 }131}132133pub(crate) fn mint_with_props_weight<T: Config>(134 create_no_data_weight: Weight,135 tokens: impl Iterator<Item = u32> + Clone,136) -> Weight {137 create_no_data_weight.saturating_add(write_token_properties_total_weight::<T, _>(138 tokens,139 <SelfWeightOf<T>>::write_token_properties,140 ))141}142143fn map_create_data<T: Config>(144 data: up_data_structs::CreateItemData,145 to: &T::CrossAccountId,146) -> Result<CreateItemData<T>, DispatchError> {147 match data {148 up_data_structs::CreateItemData::ReFungible(data) => Ok(CreateItemData::<T> {149 users: {150 let mut out = BTreeMap::new();151 out.insert(to.clone(), data.pieces);152 out.try_into().expect("limit > 0")153 },154 properties: data.properties,155 }),156 _ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),157 }158}159160161162impl<T: Config> CommonCollectionOperations<T> for RefungibleHandle<T> {163 fn create_item(164 &self,165 sender: T::CrossAccountId,166 to: T::CrossAccountId,167 data: up_data_structs::CreateItemData,168 nesting_budget: &dyn Budget,169 ) -> DispatchResultWithPostInfo {170 let weight = <CommonWeights<T>>::create_item(&data);171 with_weight(172 <Pallet<T>>::create_item(173 self,174 &sender,175 map_create_data::<T>(data, &to)?,176 nesting_budget,177 ),178 weight,179 )180 }181182 fn create_multiple_items(183 &self,184 sender: T::CrossAccountId,185 to: T::CrossAccountId,186 data: Vec<up_data_structs::CreateItemData>,187 nesting_budget: &dyn Budget,188 ) -> DispatchResultWithPostInfo {189 let weight = <CommonWeights<T>>::create_multiple_items(&data);190 let data = data191 .into_iter()192 .map(|d| map_create_data::<T>(d, &to))193 .collect::<Result<Vec<_>, DispatchError>>()?;194195 with_weight(196 <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),197 weight,198 )199 }200201 fn create_multiple_items_ex(202 &self,203 sender: <T>::CrossAccountId,204 data: CreateItemExData<T::CrossAccountId>,205 nesting_budget: &dyn Budget,206 ) -> DispatchResultWithPostInfo {207 let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);208 let data = match data {209 CreateItemExData::RefungibleMultipleOwners(CreateRefungibleExMultipleOwners {210 users,211 properties,212 }) => vec![CreateItemData::<T> { users, properties }],213 CreateItemExData::RefungibleMultipleItems(r) => r214 .into_inner()215 .into_iter()216 .map(217 |CreateRefungibleExSingleOwner {218 user,219 pieces,220 properties,221 }| CreateItemData::<T> {222 users: BTreeMap::from([(user, pieces)])223 .try_into()224 .expect("limit >= 1"),225 properties,226 },227 )228 .collect(),229 _ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),230 };231232 with_weight(233 <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),234 weight,235 )236 }237238 fn burn_item(239 &self,240 sender: T::CrossAccountId,241 token: TokenId,242 amount: u128,243 ) -> DispatchResultWithPostInfo {244 with_weight(245 <Pallet<T>>::burn(self, &sender, token, amount),246 <CommonWeights<T>>::burn_item(),247 )248 }249250 fn transfer(251 &self,252 from: T::CrossAccountId,253 to: T::CrossAccountId,254 token: TokenId,255 amount: u128,256 nesting_budget: &dyn Budget,257 ) -> DispatchResultWithPostInfo {258 with_weight(259 <Pallet<T>>::transfer(self, &from, &to, token, amount, nesting_budget),260 <CommonWeights<T>>::transfer(),261 )262 }263264 fn approve(265 &self,266 sender: T::CrossAccountId,267 spender: T::CrossAccountId,268 token: TokenId,269 amount: u128,270 ) -> DispatchResultWithPostInfo {271 with_weight(272 <Pallet<T>>::set_allowance(self, &sender, &spender, token, amount),273 <CommonWeights<T>>::approve(),274 )275 }276277 fn approve_from(278 &self,279 sender: T::CrossAccountId,280 from: T::CrossAccountId,281 to: T::CrossAccountId,282 token_id: TokenId,283 amount: u128,284 ) -> DispatchResultWithPostInfo {285 with_weight(286 <Pallet<T>>::set_allowance_from(self, &sender, &from, &to, token_id, amount),287 <CommonWeights<T>>::approve_from(),288 )289 }290291 fn transfer_from(292 &self,293 sender: T::CrossAccountId,294 from: T::CrossAccountId,295 to: T::CrossAccountId,296 token: TokenId,297 amount: u128,298 nesting_budget: &dyn Budget,299 ) -> DispatchResultWithPostInfo {300 with_weight(301 <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, amount, nesting_budget),302 <CommonWeights<T>>::transfer_from(),303 )304 }305306 fn burn_from(307 &self,308 sender: T::CrossAccountId,309 from: T::CrossAccountId,310 token: TokenId,311 amount: u128,312 nesting_budget: &dyn Budget,313 ) -> DispatchResultWithPostInfo {314 with_weight(315 <Pallet<T>>::burn_from(self, &sender, &from, token, amount, nesting_budget),316 <CommonWeights<T>>::burn_from(),317 )318 }319320 fn set_collection_properties(321 &self,322 sender: T::CrossAccountId,323 properties: Vec<Property>,324 ) -> DispatchResultWithPostInfo {325 let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);326327 with_weight(328 <Pallet<T>>::set_collection_properties(self, &sender, properties),329 weight,330 )331 }332333 fn delete_collection_properties(334 &self,335 sender: &T::CrossAccountId,336 property_keys: Vec<PropertyKey>,337 ) -> DispatchResultWithPostInfo {338 let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);339340 with_weight(341 <Pallet<T>>::delete_collection_properties(self, sender, property_keys),342 weight,343 )344 }345346 fn set_token_properties(347 &self,348 sender: T::CrossAccountId,349 token_id: TokenId,350 properties: Vec<Property>,351 nesting_budget: &dyn Budget,352 ) -> DispatchResultWithPostInfo {353 let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);354355 with_weight(356 <Pallet<T>>::set_token_properties(357 self,358 &sender,359 token_id,360 properties.into_iter(),361 nesting_budget,362 ),363 weight,364 )365 }366367 fn set_token_property_permissions(368 &self,369 sender: &T::CrossAccountId,370 property_permissions: Vec<PropertyKeyPermission>,371 ) -> DispatchResultWithPostInfo {372 let weight =373 <CommonWeights<T>>::set_token_property_permissions(property_permissions.len() as u32);374375 with_weight(376 <Pallet<T>>::set_token_property_permissions(self, sender, property_permissions),377 weight,378 )379 }380381 fn delete_token_properties(382 &self,383 sender: T::CrossAccountId,384 token_id: TokenId,385 property_keys: Vec<PropertyKey>,386 nesting_budget: &dyn Budget,387 ) -> DispatchResultWithPostInfo {388 let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);389390 with_weight(391 <Pallet<T>>::delete_token_properties(392 self,393 &sender,394 token_id,395 property_keys.into_iter(),396 nesting_budget,397 ),398 weight,399 )400 }401402 fn get_token_properties_raw(403 &self,404 token_id: TokenId,405 ) -> Option<up_data_structs::TokenProperties> {406 <TokenProperties<T>>::get((self.id, token_id))407 }408409 fn set_token_properties_raw(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {410 <TokenProperties<T>>::insert((self.id, token_id), map)411 }412413 fn check_nesting(414 &self,415 _sender: <T>::CrossAccountId,416 _from: (CollectionId, TokenId),417 _under: TokenId,418 _nesting_budget: &dyn Budget,419 ) -> sp_runtime::DispatchResult {420 fail!(<Error<T>>::RefungibleDisallowsNesting)421 }422423 fn nest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}424425 fn unnest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}426427 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {428 <Owned<T>>::iter_prefix((self.id, account))429 .map(|(id, _)| id)430 .collect()431 }432433 fn collection_tokens(&self) -> Vec<TokenId> {434 <TotalSupply<T>>::iter_prefix((self.id,))435 .map(|(id, _)| id)436 .collect()437 }438439 fn token_exists(&self, token: TokenId) -> bool {440 <Pallet<T>>::token_exists(self, token)441 }442443 fn last_token_id(&self) -> TokenId {444 TokenId(<TokensMinted<T>>::get(self.id))445 }446447 fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError> {448 <Pallet<T>>::token_owner(self.id, token)449 }450451 fn check_token_indirect_owner(452 &self,453 token: TokenId,454 maybe_owner: &T::CrossAccountId,455 nesting_budget: &dyn Budget,456 ) -> Result<bool, DispatchError> {457 let balance = self.balance(maybe_owner.clone(), token);458 let total_pieces: u128 = <Pallet<T>>::total_pieces(self.id, token).unwrap_or(u128::MAX);459 if balance != total_pieces {460 return Ok(false);461 }462463 <PalletStructure<T>>::check_indirectly_owned(464 maybe_owner.clone(),465 self.id,466 token,467 None,468 nesting_budget,469 )470 }471472 473 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {474 <Pallet<T>>::token_owners(self.id, token).unwrap_or_default()475 }476477 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {478 <Pallet<T>>::token_properties((self.id, token_id))?479 .get(key)480 .cloned()481 }482483 fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {484 let Some(properties) = <Pallet<T>>::token_properties((self.id, token_id)) else {485 return vec![];486 };487488 keys.map(|keys| {489 keys.into_iter()490 .filter_map(|key| {491 properties.get(&key).map(|value| Property {492 key,493 value: value.clone(),494 })495 })496 .collect()497 })498 .unwrap_or_else(|| {499 properties500 .into_iter()501 .map(|(key, value)| Property { key, value })502 .collect()503 })504 }505506 fn total_supply(&self) -> u32 {507 <Pallet<T>>::total_supply(self)508 }509510 fn account_balance(&self, account: T::CrossAccountId) -> u32 {511 <AccountBalance<T>>::get((self.id, account))512 }513514 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {515 <Balance<T>>::get((self.id, token, account))516 }517518 fn allowance(519 &self,520 sender: T::CrossAccountId,521 spender: T::CrossAccountId,522 token: TokenId,523 ) -> u128 {524 <Allowance<T>>::get((self.id, token, sender, spender))525 }526527 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {528 Some(self)529 }530531 fn total_pieces(&self, token: TokenId) -> Option<u128> {532 <Pallet<T>>::total_pieces(self.id, token)533 }534535 fn set_allowance_for_all(536 &self,537 owner: T::CrossAccountId,538 operator: T::CrossAccountId,539 approve: bool,540 ) -> DispatchResultWithPostInfo {541 with_weight(542 <Pallet<T>>::set_allowance_for_all(self, &owner, &operator, approve),543 <CommonWeights<T>>::set_allowance_for_all(),544 )545 }546547 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool {548 <Pallet<T>>::allowance_for_all(self, &owner, &operator)549 }550551 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo {552 with_weight(553 <Pallet<T>>::repair_item(self, token),554 <CommonWeights<T>>::force_repair_item(),555 )556 }557}558559impl<T: Config> RefungibleExtensions<T> for RefungibleHandle<T> {560 fn repartition(561 &self,562 owner: &T::CrossAccountId,563 token: TokenId,564 amount: u128,565 ) -> DispatchResultWithPostInfo {566 with_weight(567 <Pallet<T>>::repartition(self, owner, token, amount),568 <SelfWeightOf<T>>::repartition_item(),569 )570 }571}