1234567891011121314151617use core::marker::PhantomData;1819use sp_std::collections::btree_map::BTreeMap;20use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};21use up_data_structs::{22 CollectionId, TokenId, CreateItemExData, budget::Budget, Property, PropertyKey, PropertyValue,23 PropertyKeyPermission, CollectionPropertiesVec, CreateRefungibleExMultipleOwners,24 CreateRefungibleExSingleOwner,25};26use pallet_common::{27 CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,28 weights::WeightInfo as _,29};30use pallet_structure::Error as StructureError;31use sp_runtime::{DispatchError};32use sp_std::{vec::Vec, vec};3334use crate::{35 AccountBalance, Allowance, Balance, Config, Error, Owned, Pallet, RefungibleHandle,36 SelfWeightOf, weights::WeightInfo, TokensMinted, TotalSupply, CreateItemData,37};3839macro_rules! max_weight_of {40 ($($method:ident ($($args:tt)*)),*) => {41 042 $(43 .max(<SelfWeightOf<T>>::$method($($args)*))44 )*45 };46}4748fn properties_weight<T: Config>(properties: &CollectionPropertiesVec) -> u64 {49 if properties.len() > 0 {50 <CommonWeights<T>>::set_token_properties(properties.len() as u32)51 } else {52 053 }54}5556pub struct CommonWeights<T: Config>(PhantomData<T>);57impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {58 fn create_item() -> Weight {59 <SelfWeightOf<T>>::create_item()60 }6162 fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {63 <SelfWeightOf<T>>::create_multiple_items(data.len() as u32).saturating_add(64 data.iter()65 .map(|data| match data {66 up_data_structs::CreateItemData::ReFungible(rft_data) => {67 properties_weight::<T>(&rft_data.properties)68 }69 _ => 0,70 })71 .fold(0, |a, b| a.saturating_add(b)),72 )73 }7475 fn create_multiple_items_ex(call: &CreateItemExData<T::CrossAccountId>) -> Weight {76 match call {77 CreateItemExData::RefungibleMultipleOwners(i) => {78 <SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(i.users.len() as u32)79 .saturating_add(properties_weight::<T>(&i.properties))80 }81 CreateItemExData::RefungibleMultipleItems(i) => {82 <SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(i.len() as u32)83 .saturating_add(84 i.iter()85 .map(|d| properties_weight::<T>(&d.properties))86 .fold(0, |a, b| a.saturating_add(b)),87 )88 }89 _ => 0,90 }91 }9293 fn burn_item() -> Weight {94 max_weight_of!(burn_item_partial(), burn_item_fully())95 }9697 fn set_collection_properties(amount: u32) -> Weight {98 <pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)99 }100101 fn delete_collection_properties(amount: u32) -> Weight {102 <pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)103 }104105 fn set_token_properties(amount: u32) -> Weight {106 <SelfWeightOf<T>>::set_token_properties(amount)107 }108109 fn delete_token_properties(amount: u32) -> Weight {110 <SelfWeightOf<T>>::delete_token_properties(amount)111 }112113 fn set_token_property_permissions(amount: u32) -> Weight {114 <SelfWeightOf<T>>::set_token_property_permissions(amount)115 }116117 fn transfer() -> Weight {118 max_weight_of!(119 transfer_normal(),120 transfer_creating(),121 transfer_removing(),122 transfer_creating_removing()123 )124 }125126 fn approve() -> Weight {127 <SelfWeightOf<T>>::approve()128 }129130 fn transfer_from() -> Weight {131 max_weight_of!(132 transfer_from_normal(),133 transfer_from_creating(),134 transfer_from_removing(),135 transfer_from_creating_removing()136 )137 }138139 fn burn_from() -> Weight {140 <SelfWeightOf<T>>::burn_from()141 }142143 fn burn_recursively_self_raw() -> Weight {144 145 Self::burn_item() + T::DbWeight::get().reads(1)146 }147 fn burn_recursively_breadth_raw(_amount: u32) -> Weight {148 149 0150 }151}152153fn map_create_data<T: Config>(154 data: up_data_structs::CreateItemData,155 to: &T::CrossAccountId,156) -> Result<CreateItemData<T::CrossAccountId>, DispatchError> {157 match data {158 up_data_structs::CreateItemData::ReFungible(data) => Ok(CreateItemData {159 users: {160 let mut out = BTreeMap::new();161 out.insert(to.clone(), data.pieces);162 out.try_into().expect("limit > 0")163 },164 properties: data.properties,165 }),166 _ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),167 }168}169170171172impl<T: Config> CommonCollectionOperations<T> for RefungibleHandle<T> {173 fn create_item(174 &self,175 sender: T::CrossAccountId,176 to: T::CrossAccountId,177 data: up_data_structs::CreateItemData,178 nesting_budget: &dyn Budget,179 ) -> DispatchResultWithPostInfo {180 with_weight(181 <Pallet<T>>::create_item(182 self,183 &sender,184 map_create_data::<T>(data, &to)?,185 nesting_budget,186 ),187 <CommonWeights<T>>::create_item(),188 )189 }190191 fn create_multiple_items(192 &self,193 sender: T::CrossAccountId,194 to: T::CrossAccountId,195 data: Vec<up_data_structs::CreateItemData>,196 nesting_budget: &dyn Budget,197 ) -> DispatchResultWithPostInfo {198 let weight = <CommonWeights<T>>::create_multiple_items(&data);199 let data = data200 .into_iter()201 .map(|d| map_create_data::<T>(d, &to))202 .collect::<Result<Vec<_>, DispatchError>>()?;203204 with_weight(205 <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),206 weight,207 )208 }209210 fn create_multiple_items_ex(211 &self,212 sender: <T>::CrossAccountId,213 data: CreateItemExData<T::CrossAccountId>,214 nesting_budget: &dyn Budget,215 ) -> DispatchResultWithPostInfo {216 let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);217 let data = match data {218 CreateItemExData::RefungibleMultipleOwners(CreateRefungibleExMultipleOwners {219 users,220 properties,221 }) => vec![CreateItemData { users, properties }],222 CreateItemExData::RefungibleMultipleItems(r) => r223 .into_inner()224 .into_iter()225 .map(226 |CreateRefungibleExSingleOwner {227 user,228 pieces,229 properties,230 }| CreateItemData {231 users: BTreeMap::from([(user, pieces)])232 .try_into()233 .expect("limit >= 1"),234 properties,235 },236 )237 .collect(),238 _ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),239 };240241 with_weight(242 <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),243 weight,244 )245 }246247 fn burn_item(248 &self,249 sender: T::CrossAccountId,250 token: TokenId,251 amount: u128,252 ) -> DispatchResultWithPostInfo {253 with_weight(254 <Pallet<T>>::burn(self, &sender, token, amount),255 <CommonWeights<T>>::burn_item(),256 )257 }258259 fn burn_item_recursively(260 &self,261 sender: T::CrossAccountId,262 token: TokenId,263 self_budget: &dyn Budget,264 _breadth_budget: &dyn Budget,265 ) -> DispatchResultWithPostInfo {266 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);267 with_weight(268 <Pallet<T>>::burn(269 self,270 &sender,271 token,272 <Balance<T>>::get((self.id, token, &sender)),273 ),274 <CommonWeights<T>>::burn_recursively_self_raw(),275 )276 }277278 fn transfer(279 &self,280 from: T::CrossAccountId,281 to: T::CrossAccountId,282 token: TokenId,283 amount: u128,284 nesting_budget: &dyn Budget,285 ) -> DispatchResultWithPostInfo {286 with_weight(287 <Pallet<T>>::transfer(self, &from, &to, token, amount, nesting_budget),288 <CommonWeights<T>>::transfer(),289 )290 }291292 fn approve(293 &self,294 sender: T::CrossAccountId,295 spender: T::CrossAccountId,296 token: TokenId,297 amount: u128,298 ) -> DispatchResultWithPostInfo {299 with_weight(300 <Pallet<T>>::set_allowance(self, &sender, &spender, token, amount),301 <CommonWeights<T>>::approve(),302 )303 }304305 fn transfer_from(306 &self,307 sender: T::CrossAccountId,308 from: T::CrossAccountId,309 to: T::CrossAccountId,310 token: TokenId,311 amount: u128,312 nesting_budget: &dyn Budget,313 ) -> DispatchResultWithPostInfo {314 with_weight(315 <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, amount, nesting_budget),316 <CommonWeights<T>>::transfer_from(),317 )318 }319320 fn burn_from(321 &self,322 sender: T::CrossAccountId,323 from: T::CrossAccountId,324 token: TokenId,325 amount: u128,326 nesting_budget: &dyn Budget,327 ) -> DispatchResultWithPostInfo {328 with_weight(329 <Pallet<T>>::burn_from(self, &sender, &from, token, amount, nesting_budget),330 <CommonWeights<T>>::burn_from(),331 )332 }333334 fn set_collection_properties(335 &self,336 sender: T::CrossAccountId,337 properties: Vec<Property>,338 ) -> DispatchResultWithPostInfo {339 let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);340341 with_weight(342 <Pallet<T>>::set_collection_properties(self, &sender, properties),343 weight,344 )345 }346347 fn delete_collection_properties(348 &self,349 sender: &T::CrossAccountId,350 property_keys: Vec<PropertyKey>,351 ) -> DispatchResultWithPostInfo {352 let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);353354 with_weight(355 <Pallet<T>>::delete_collection_properties(self, sender, property_keys),356 weight,357 )358 }359360 fn set_token_properties(361 &self,362 sender: T::CrossAccountId,363 token_id: TokenId,364 properties: Vec<Property>,365 nesting_budget: &dyn Budget,366 ) -> DispatchResultWithPostInfo {367 let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);368369 with_weight(370 <Pallet<T>>::set_token_properties(371 self,372 &sender,373 token_id,374 properties.into_iter(),375 false,376 nesting_budget,377 ),378 weight,379 )380 }381382 fn set_token_property_permissions(383 &self,384 sender: &T::CrossAccountId,385 property_permissions: Vec<PropertyKeyPermission>,386 ) -> DispatchResultWithPostInfo {387 let weight =388 <CommonWeights<T>>::set_token_property_permissions(property_permissions.len() as u32);389390 with_weight(391 <Pallet<T>>::set_token_property_permissions(self, sender, property_permissions),392 weight,393 )394 }395396 fn delete_token_properties(397 &self,398 sender: T::CrossAccountId,399 token_id: TokenId,400 property_keys: Vec<PropertyKey>,401 nesting_budget: &dyn Budget,402 ) -> DispatchResultWithPostInfo {403 let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);404405 with_weight(406 <Pallet<T>>::delete_token_properties(407 self,408 &sender,409 token_id,410 property_keys.into_iter(),411 nesting_budget,412 ),413 weight,414 )415 }416417 fn check_nesting(418 &self,419 _sender: <T>::CrossAccountId,420 _from: (CollectionId, TokenId),421 _under: TokenId,422 _nesting_budget: &dyn Budget,423 ) -> sp_runtime::DispatchResult {424 fail!(<Error<T>>::RefungibleDisallowsNesting)425 }426427 fn nest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}428429 fn unnest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}430431 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {432 <Owned<T>>::iter_prefix((self.id, account))433 .map(|(id, _)| id)434 .collect()435 }436437 fn collection_tokens(&self) -> Vec<TokenId> {438 <TotalSupply<T>>::iter_prefix((self.id,))439 .map(|(id, _)| id)440 .collect()441 }442443 fn token_exists(&self, token: TokenId) -> bool {444 <Pallet<T>>::token_exists(self, token)445 }446447 fn last_token_id(&self) -> TokenId {448 TokenId(<TokensMinted<T>>::get(self.id))449 }450451 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {452 <Pallet<T>>::token_owner(self.id, token)453 }454455 456 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {457 <Pallet<T>>::token_owners(self.id, token).unwrap_or_default()458 }459460 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {461 <Pallet<T>>::token_properties((self.id, token_id))462 .get(key)463 .cloned()464 }465466 fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {467 let properties = <Pallet<T>>::token_properties((self.id, token_id));468469 keys.map(|keys| {470 keys.into_iter()471 .filter_map(|key| {472 properties.get(&key).map(|value| Property {473 key,474 value: value.clone(),475 })476 })477 .collect()478 })479 .unwrap_or_else(|| {480 properties481 .into_iter()482 .map(|(key, value)| Property { key, value })483 .collect()484 })485 }486487 fn total_supply(&self) -> u32 {488 <Pallet<T>>::total_supply(self)489 }490491 fn account_balance(&self, account: T::CrossAccountId) -> u32 {492 <AccountBalance<T>>::get((self.id, account))493 }494495 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {496 <Balance<T>>::get((self.id, token, account))497 }498499 fn allowance(500 &self,501 sender: T::CrossAccountId,502 spender: T::CrossAccountId,503 token: TokenId,504 ) -> u128 {505 <Allowance<T>>::get((self.id, token, sender, spender))506 }507508 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {509 Some(self)510 }511512 fn total_pieces(&self, token: TokenId) -> Option<u128> {513 <Pallet<T>>::total_pieces(self.id, token)514 }515}516517impl<T: Config> RefungibleExtensions<T> for RefungibleHandle<T> {518 fn repartition(519 &self,520 owner: &T::CrossAccountId,521 token: TokenId,522 amount: u128,523 ) -> DispatchResultWithPostInfo {524 with_weight(525 <Pallet<T>>::repartition(self, owner, token, amount),526 <SelfWeightOf<T>>::repartition_item(),527 )528 }529}