difftreelog
Merge pull request #785 from UniqueNetwork/feature/force-repair-things
in: master
12 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -1223,7 +1223,7 @@
}
/// Set a scoped collection property, where the scope is a special prefix
- /// prohibiting a user to change the property.
+ /// prohibiting a user access to change the property directly.
///
/// * `collection_id` - ID of the collection for which the property is being set.
/// * `scope` - Property scope.
@@ -1242,7 +1242,7 @@
}
/// Set scoped collection properties, where the scope is a special prefix
- /// prohibiting a user to change the properties.
+ /// prohibiting a user access to change the properties directly.
///
/// * `collection_id` - ID of the collection for which the properties is being set.
/// * `scope` - Property scope.
@@ -1730,6 +1730,15 @@
);
Ok(new_permission)
}
+
+ /// Repair possibly broken properties of a collection.
+ pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {
+ CollectionProperties::<T>::mutate(collection_id, |properties| {
+ properties.recompute_consumed_space();
+ });
+
+ Ok(())
+ }
}
/// Indicates unsupported methods by returning [Error::UnsupportedOperation].
@@ -1819,7 +1828,7 @@
fn set_allowance_for_all() -> Weight;
/// The price of repairing an item.
- fn repair_item() -> Weight;
+ fn force_repair_item() -> Weight;
}
/// Weight info extension trait for refungible pallet.
pallets/fungible/src/common.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use core::marker::PhantomData;1819use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};20use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget, CreateItemData};21use pallet_common::{22 CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,23 weights::WeightInfo as _,24};25use pallet_structure::Error as StructureError;26use sp_runtime::ArithmeticError;27use sp_std::{vec::Vec, vec};28use up_data_structs::{Property, PropertyKey, PropertyValue, PropertyKeyPermission};2930use crate::{31 Allowance, TotalSupply, Balance, Config, Error, FungibleHandle, Pallet, SelfWeightOf,32 weights::WeightInfo,33};3435pub struct CommonWeights<T: Config>(PhantomData<T>);36impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {37 fn create_item() -> Weight {38 <SelfWeightOf<T>>::create_item()39 }4041 fn create_multiple_items(_data: &[CreateItemData]) -> Weight {42 // All items minted for the same user, so it works same as create_item43 Self::create_item()44 }4546 fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {47 match data {48 CreateItemExData::Fungible(f) => {49 <SelfWeightOf<T>>::create_multiple_items_ex(f.len() as u32)50 }51 _ => Weight::zero(),52 }53 }5455 fn burn_item() -> Weight {56 <SelfWeightOf<T>>::burn_item()57 }5859 fn set_collection_properties(amount: u32) -> Weight {60 <pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)61 }6263 fn delete_collection_properties(amount: u32) -> Weight {64 <pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)65 }6667 fn set_token_properties(_amount: u32) -> Weight {68 // Error69 Weight::zero()70 }7172 fn delete_token_properties(_amount: u32) -> Weight {73 // Error74 Weight::zero()75 }7677 fn set_token_property_permissions(_amount: u32) -> Weight {78 // Error79 Weight::zero()80 }8182 fn transfer() -> Weight {83 <SelfWeightOf<T>>::transfer()84 }8586 fn approve() -> Weight {87 <SelfWeightOf<T>>::approve()88 }8990 fn transfer_from() -> Weight {91 <SelfWeightOf<T>>::transfer_from()92 }9394 fn burn_from() -> Weight {95 <SelfWeightOf<T>>::burn_from()96 }9798 fn burn_recursively_self_raw() -> Weight {99 // Read to get total balance100 Self::burn_item() + T::DbWeight::get().reads(1)101 }102103 fn burn_recursively_breadth_raw(_amount: u32) -> Weight {104 // Fungible tokens can't have children105 Weight::zero()106 }107108 fn token_owner() -> Weight {109 Weight::zero()110 }111112 fn set_allowance_for_all() -> Weight {113 Weight::zero()114 }115116 fn repair_item() -> Weight {117 Weight::zero()118 }119}120121/// Implementation of `CommonCollectionOperations` for `FungibleHandle`. It wraps FungibleHandle Pallete122/// methods and adds weight info.123impl<T: Config> CommonCollectionOperations<T> for FungibleHandle<T> {124 fn create_item(125 &self,126 sender: T::CrossAccountId,127 to: T::CrossAccountId,128 data: up_data_structs::CreateItemData,129 nesting_budget: &dyn Budget,130 ) -> DispatchResultWithPostInfo {131 match data {132 up_data_structs::CreateItemData::Fungible(data) => with_weight(133 <Pallet<T>>::create_item(self, &sender, (to, data.value), nesting_budget),134 <CommonWeights<T>>::create_item(),135 ),136 _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),137 }138 }139140 fn create_multiple_items(141 &self,142 sender: T::CrossAccountId,143 to: T::CrossAccountId,144 data: Vec<up_data_structs::CreateItemData>,145 nesting_budget: &dyn Budget,146 ) -> DispatchResultWithPostInfo {147 let mut sum: u128 = 0;148 for data in data {149 match data {150 up_data_structs::CreateItemData::Fungible(data) => {151 sum = sum152 .checked_add(data.value)153 .ok_or(ArithmeticError::Overflow)?;154 }155 _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),156 }157 }158159 with_weight(160 <Pallet<T>>::create_item(self, &sender, (to, sum), nesting_budget),161 <CommonWeights<T>>::create_item(),162 )163 }164165 fn create_multiple_items_ex(166 &self,167 sender: <T>::CrossAccountId,168 data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,169 nesting_budget: &dyn Budget,170 ) -> DispatchResultWithPostInfo {171 let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);172 let data = match data {173 up_data_structs::CreateItemExData::Fungible(f) => f,174 _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),175 };176177 with_weight(178 <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),179 weight,180 )181 }182183 fn burn_item(184 &self,185 sender: T::CrossAccountId,186 token: TokenId,187 amount: u128,188 ) -> DispatchResultWithPostInfo {189 ensure!(190 token == TokenId::default(),191 <Error<T>>::FungibleItemsHaveNoId192 );193194 with_weight(195 <Pallet<T>>::burn(self, &sender, amount),196 <CommonWeights<T>>::burn_item(),197 )198 }199200 fn burn_item_recursively(201 &self,202 sender: T::CrossAccountId,203 token: TokenId,204 self_budget: &dyn Budget,205 _breadth_budget: &dyn Budget,206 ) -> DispatchResultWithPostInfo {207 // Should not happen?208 ensure!(209 token == TokenId::default(),210 <Error<T>>::FungibleItemsHaveNoId211 );212 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);213214 with_weight(215 <Pallet<T>>::burn(self, &sender, <Balance<T>>::get((self.id, &sender))),216 <CommonWeights<T>>::burn_recursively_self_raw(),217 )218 }219220 fn transfer(221 &self,222 from: T::CrossAccountId,223 to: T::CrossAccountId,224 token: TokenId,225 amount: u128,226 nesting_budget: &dyn Budget,227 ) -> DispatchResultWithPostInfo {228 ensure!(229 token == TokenId::default(),230 <Error<T>>::FungibleItemsHaveNoId231 );232233 with_weight(234 <Pallet<T>>::transfer(self, &from, &to, amount, nesting_budget),235 <CommonWeights<T>>::transfer(),236 )237 }238239 fn approve(240 &self,241 sender: T::CrossAccountId,242 spender: T::CrossAccountId,243 token: TokenId,244 amount: u128,245 ) -> DispatchResultWithPostInfo {246 ensure!(247 token == TokenId::default(),248 <Error<T>>::FungibleItemsHaveNoId249 );250251 with_weight(252 <Pallet<T>>::set_allowance(self, &sender, &spender, amount),253 <CommonWeights<T>>::approve(),254 )255 }256257 fn transfer_from(258 &self,259 sender: T::CrossAccountId,260 from: T::CrossAccountId,261 to: T::CrossAccountId,262 token: TokenId,263 amount: u128,264 nesting_budget: &dyn Budget,265 ) -> DispatchResultWithPostInfo {266 ensure!(267 token == TokenId::default(),268 <Error<T>>::FungibleItemsHaveNoId269 );270271 with_weight(272 <Pallet<T>>::transfer_from(self, &sender, &from, &to, amount, nesting_budget),273 <CommonWeights<T>>::transfer_from(),274 )275 }276277 fn burn_from(278 &self,279 sender: T::CrossAccountId,280 from: T::CrossAccountId,281 token: TokenId,282 amount: u128,283 nesting_budget: &dyn Budget,284 ) -> DispatchResultWithPostInfo {285 ensure!(286 token == TokenId::default(),287 <Error<T>>::FungibleItemsHaveNoId288 );289290 with_weight(291 <Pallet<T>>::burn_from(self, &sender, &from, amount, nesting_budget),292 <CommonWeights<T>>::burn_from(),293 )294 }295296 fn set_collection_properties(297 &self,298 sender: T::CrossAccountId,299 properties: Vec<Property>,300 ) -> DispatchResultWithPostInfo {301 let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);302303 with_weight(304 <Pallet<T>>::set_collection_properties(self, &sender, properties),305 weight,306 )307 }308309 fn delete_collection_properties(310 &self,311 sender: &T::CrossAccountId,312 property_keys: Vec<PropertyKey>,313 ) -> DispatchResultWithPostInfo {314 let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);315316 with_weight(317 <Pallet<T>>::delete_collection_properties(self, sender, property_keys),318 weight,319 )320 }321322 fn set_token_properties(323 &self,324 _sender: T::CrossAccountId,325 _token_id: TokenId,326 _property: Vec<Property>,327 _nesting_budget: &dyn Budget,328 ) -> DispatchResultWithPostInfo {329 fail!(<Error<T>>::SettingPropertiesNotAllowed)330 }331332 fn set_token_property_permissions(333 &self,334 _sender: &T::CrossAccountId,335 _property_permissions: Vec<PropertyKeyPermission>,336 ) -> DispatchResultWithPostInfo {337 fail!(<Error<T>>::SettingPropertiesNotAllowed)338 }339340 fn delete_token_properties(341 &self,342 _sender: T::CrossAccountId,343 _token_id: TokenId,344 _property_keys: Vec<PropertyKey>,345 _nesting_budget: &dyn Budget,346 ) -> DispatchResultWithPostInfo {347 fail!(<Error<T>>::SettingPropertiesNotAllowed)348 }349350 fn check_nesting(351 &self,352 _sender: <T>::CrossAccountId,353 _from: (CollectionId, TokenId),354 _under: TokenId,355 _nesting_budget: &dyn Budget,356 ) -> sp_runtime::DispatchResult {357 fail!(<Error<T>>::FungibleDisallowsNesting)358 }359360 fn nest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}361362 fn unnest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}363364 fn collection_tokens(&self) -> Vec<TokenId> {365 vec![TokenId::default()]366 }367368 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {369 if <Balance<T>>::get((self.id, account)) != 0 {370 vec![TokenId::default()]371 } else {372 vec![]373 }374 }375376 fn token_exists(&self, token: TokenId) -> bool {377 token == TokenId::default()378 }379380 fn last_token_id(&self) -> TokenId {381 TokenId::default()382 }383384 fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {385 None386 }387388 /// Returns 10 tokens owners in no particular order.389 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {390 <Pallet<T>>::token_owners(self.id, token).unwrap_or_default()391 }392393 fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {394 None395 }396397 fn token_properties(398 &self,399 _token_id: TokenId,400 _keys: Option<Vec<PropertyKey>>,401 ) -> Vec<Property> {402 Vec::new()403 }404405 fn total_supply(&self) -> u32 {406 1407 }408409 fn account_balance(&self, account: T::CrossAccountId) -> u32 {410 if <Balance<T>>::get((self.id, account)) != 0 {411 1412 } else {413 0414 }415 }416417 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {418 if token != TokenId::default() {419 return 0;420 }421 <Balance<T>>::get((self.id, account))422 }423424 fn allowance(425 &self,426 sender: T::CrossAccountId,427 spender: T::CrossAccountId,428 token: TokenId,429 ) -> u128 {430 if token != TokenId::default() {431 return 0;432 }433 <Allowance<T>>::get((self.id, sender, spender))434 }435436 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {437 None438 }439440 fn total_pieces(&self, token: TokenId) -> Option<u128> {441 if token != TokenId::default() {442 return None;443 }444 <TotalSupply<T>>::try_get(self.id).ok()445 }446447 fn set_allowance_for_all(448 &self,449 _owner: T::CrossAccountId,450 _operator: T::CrossAccountId,451 _approve: bool,452 ) -> DispatchResultWithPostInfo {453 fail!(<Error<T>>::SettingAllowanceForAllNotAllowed)454 }455456 fn allowance_for_all(&self, _owner: T::CrossAccountId, _operator: T::CrossAccountId) -> bool {457 false458 }459460 /// Repairs a possibly broken item.461 fn repair_item(&self, _token: TokenId) -> DispatchResultWithPostInfo {462 fail!(<Error<T>>::FungibleTokensAreAlwaysValid)463 }464}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use core::marker::PhantomData;1819use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};20use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget, CreateItemData};21use pallet_common::{22 CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,23 weights::WeightInfo as _,24};25use pallet_structure::Error as StructureError;26use sp_runtime::ArithmeticError;27use sp_std::{vec::Vec, vec};28use up_data_structs::{Property, PropertyKey, PropertyValue, PropertyKeyPermission};2930use crate::{31 Allowance, TotalSupply, Balance, Config, Error, FungibleHandle, Pallet, SelfWeightOf,32 weights::WeightInfo,33};3435pub struct CommonWeights<T: Config>(PhantomData<T>);36impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {37 fn create_item() -> Weight {38 <SelfWeightOf<T>>::create_item()39 }4041 fn create_multiple_items(_data: &[CreateItemData]) -> Weight {42 // All items minted for the same user, so it works same as create_item43 Self::create_item()44 }4546 fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {47 match data {48 CreateItemExData::Fungible(f) => {49 <SelfWeightOf<T>>::create_multiple_items_ex(f.len() as u32)50 }51 _ => Weight::zero(),52 }53 }5455 fn burn_item() -> Weight {56 <SelfWeightOf<T>>::burn_item()57 }5859 fn set_collection_properties(amount: u32) -> Weight {60 <pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)61 }6263 fn delete_collection_properties(amount: u32) -> Weight {64 <pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)65 }6667 fn set_token_properties(_amount: u32) -> Weight {68 // Error69 Weight::zero()70 }7172 fn delete_token_properties(_amount: u32) -> Weight {73 // Error74 Weight::zero()75 }7677 fn set_token_property_permissions(_amount: u32) -> Weight {78 // Error79 Weight::zero()80 }8182 fn transfer() -> Weight {83 <SelfWeightOf<T>>::transfer()84 }8586 fn approve() -> Weight {87 <SelfWeightOf<T>>::approve()88 }8990 fn transfer_from() -> Weight {91 <SelfWeightOf<T>>::transfer_from()92 }9394 fn burn_from() -> Weight {95 <SelfWeightOf<T>>::burn_from()96 }9798 fn burn_recursively_self_raw() -> Weight {99 // Read to get total balance100 Self::burn_item() + T::DbWeight::get().reads(1)101 }102103 fn burn_recursively_breadth_raw(_amount: u32) -> Weight {104 // Fungible tokens can't have children105 Weight::zero()106 }107108 fn token_owner() -> Weight {109 Weight::zero()110 }111112 fn set_allowance_for_all() -> Weight {113 Weight::zero()114 }115116 fn force_repair_item() -> Weight {117 Weight::zero()118 }119}120121/// Implementation of `CommonCollectionOperations` for `FungibleHandle`. It wraps FungibleHandle Pallete122/// methods and adds weight info.123impl<T: Config> CommonCollectionOperations<T> for FungibleHandle<T> {124 fn create_item(125 &self,126 sender: T::CrossAccountId,127 to: T::CrossAccountId,128 data: up_data_structs::CreateItemData,129 nesting_budget: &dyn Budget,130 ) -> DispatchResultWithPostInfo {131 match data {132 up_data_structs::CreateItemData::Fungible(data) => with_weight(133 <Pallet<T>>::create_item(self, &sender, (to, data.value), nesting_budget),134 <CommonWeights<T>>::create_item(),135 ),136 _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),137 }138 }139140 fn create_multiple_items(141 &self,142 sender: T::CrossAccountId,143 to: T::CrossAccountId,144 data: Vec<up_data_structs::CreateItemData>,145 nesting_budget: &dyn Budget,146 ) -> DispatchResultWithPostInfo {147 let mut sum: u128 = 0;148 for data in data {149 match data {150 up_data_structs::CreateItemData::Fungible(data) => {151 sum = sum152 .checked_add(data.value)153 .ok_or(ArithmeticError::Overflow)?;154 }155 _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),156 }157 }158159 with_weight(160 <Pallet<T>>::create_item(self, &sender, (to, sum), nesting_budget),161 <CommonWeights<T>>::create_item(),162 )163 }164165 fn create_multiple_items_ex(166 &self,167 sender: <T>::CrossAccountId,168 data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,169 nesting_budget: &dyn Budget,170 ) -> DispatchResultWithPostInfo {171 let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);172 let data = match data {173 up_data_structs::CreateItemExData::Fungible(f) => f,174 _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),175 };176177 with_weight(178 <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),179 weight,180 )181 }182183 fn burn_item(184 &self,185 sender: T::CrossAccountId,186 token: TokenId,187 amount: u128,188 ) -> DispatchResultWithPostInfo {189 ensure!(190 token == TokenId::default(),191 <Error<T>>::FungibleItemsHaveNoId192 );193194 with_weight(195 <Pallet<T>>::burn(self, &sender, amount),196 <CommonWeights<T>>::burn_item(),197 )198 }199200 fn burn_item_recursively(201 &self,202 sender: T::CrossAccountId,203 token: TokenId,204 self_budget: &dyn Budget,205 _breadth_budget: &dyn Budget,206 ) -> DispatchResultWithPostInfo {207 // Should not happen?208 ensure!(209 token == TokenId::default(),210 <Error<T>>::FungibleItemsHaveNoId211 );212 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);213214 with_weight(215 <Pallet<T>>::burn(self, &sender, <Balance<T>>::get((self.id, &sender))),216 <CommonWeights<T>>::burn_recursively_self_raw(),217 )218 }219220 fn transfer(221 &self,222 from: T::CrossAccountId,223 to: T::CrossAccountId,224 token: TokenId,225 amount: u128,226 nesting_budget: &dyn Budget,227 ) -> DispatchResultWithPostInfo {228 ensure!(229 token == TokenId::default(),230 <Error<T>>::FungibleItemsHaveNoId231 );232233 with_weight(234 <Pallet<T>>::transfer(self, &from, &to, amount, nesting_budget),235 <CommonWeights<T>>::transfer(),236 )237 }238239 fn approve(240 &self,241 sender: T::CrossAccountId,242 spender: T::CrossAccountId,243 token: TokenId,244 amount: u128,245 ) -> DispatchResultWithPostInfo {246 ensure!(247 token == TokenId::default(),248 <Error<T>>::FungibleItemsHaveNoId249 );250251 with_weight(252 <Pallet<T>>::set_allowance(self, &sender, &spender, amount),253 <CommonWeights<T>>::approve(),254 )255 }256257 fn transfer_from(258 &self,259 sender: T::CrossAccountId,260 from: T::CrossAccountId,261 to: T::CrossAccountId,262 token: TokenId,263 amount: u128,264 nesting_budget: &dyn Budget,265 ) -> DispatchResultWithPostInfo {266 ensure!(267 token == TokenId::default(),268 <Error<T>>::FungibleItemsHaveNoId269 );270271 with_weight(272 <Pallet<T>>::transfer_from(self, &sender, &from, &to, amount, nesting_budget),273 <CommonWeights<T>>::transfer_from(),274 )275 }276277 fn burn_from(278 &self,279 sender: T::CrossAccountId,280 from: T::CrossAccountId,281 token: TokenId,282 amount: u128,283 nesting_budget: &dyn Budget,284 ) -> DispatchResultWithPostInfo {285 ensure!(286 token == TokenId::default(),287 <Error<T>>::FungibleItemsHaveNoId288 );289290 with_weight(291 <Pallet<T>>::burn_from(self, &sender, &from, amount, nesting_budget),292 <CommonWeights<T>>::burn_from(),293 )294 }295296 fn set_collection_properties(297 &self,298 sender: T::CrossAccountId,299 properties: Vec<Property>,300 ) -> DispatchResultWithPostInfo {301 let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);302303 with_weight(304 <Pallet<T>>::set_collection_properties(self, &sender, properties),305 weight,306 )307 }308309 fn delete_collection_properties(310 &self,311 sender: &T::CrossAccountId,312 property_keys: Vec<PropertyKey>,313 ) -> DispatchResultWithPostInfo {314 let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);315316 with_weight(317 <Pallet<T>>::delete_collection_properties(self, sender, property_keys),318 weight,319 )320 }321322 fn set_token_properties(323 &self,324 _sender: T::CrossAccountId,325 _token_id: TokenId,326 _property: Vec<Property>,327 _nesting_budget: &dyn Budget,328 ) -> DispatchResultWithPostInfo {329 fail!(<Error<T>>::SettingPropertiesNotAllowed)330 }331332 fn set_token_property_permissions(333 &self,334 _sender: &T::CrossAccountId,335 _property_permissions: Vec<PropertyKeyPermission>,336 ) -> DispatchResultWithPostInfo {337 fail!(<Error<T>>::SettingPropertiesNotAllowed)338 }339340 fn delete_token_properties(341 &self,342 _sender: T::CrossAccountId,343 _token_id: TokenId,344 _property_keys: Vec<PropertyKey>,345 _nesting_budget: &dyn Budget,346 ) -> DispatchResultWithPostInfo {347 fail!(<Error<T>>::SettingPropertiesNotAllowed)348 }349350 fn check_nesting(351 &self,352 _sender: <T>::CrossAccountId,353 _from: (CollectionId, TokenId),354 _under: TokenId,355 _nesting_budget: &dyn Budget,356 ) -> sp_runtime::DispatchResult {357 fail!(<Error<T>>::FungibleDisallowsNesting)358 }359360 fn nest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}361362 fn unnest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}363364 fn collection_tokens(&self) -> Vec<TokenId> {365 vec![TokenId::default()]366 }367368 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {369 if <Balance<T>>::get((self.id, account)) != 0 {370 vec![TokenId::default()]371 } else {372 vec![]373 }374 }375376 fn token_exists(&self, token: TokenId) -> bool {377 token == TokenId::default()378 }379380 fn last_token_id(&self) -> TokenId {381 TokenId::default()382 }383384 fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {385 None386 }387388 /// Returns 10 tokens owners in no particular order.389 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {390 <Pallet<T>>::token_owners(self.id, token).unwrap_or_default()391 }392393 fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {394 None395 }396397 fn token_properties(398 &self,399 _token_id: TokenId,400 _keys: Option<Vec<PropertyKey>>,401 ) -> Vec<Property> {402 Vec::new()403 }404405 fn total_supply(&self) -> u32 {406 1407 }408409 fn account_balance(&self, account: T::CrossAccountId) -> u32 {410 if <Balance<T>>::get((self.id, account)) != 0 {411 1412 } else {413 0414 }415 }416417 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {418 if token != TokenId::default() {419 return 0;420 }421 <Balance<T>>::get((self.id, account))422 }423424 fn allowance(425 &self,426 sender: T::CrossAccountId,427 spender: T::CrossAccountId,428 token: TokenId,429 ) -> u128 {430 if token != TokenId::default() {431 return 0;432 }433 <Allowance<T>>::get((self.id, sender, spender))434 }435436 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {437 None438 }439440 fn total_pieces(&self, token: TokenId) -> Option<u128> {441 if token != TokenId::default() {442 return None;443 }444 <TotalSupply<T>>::try_get(self.id).ok()445 }446447 fn set_allowance_for_all(448 &self,449 _owner: T::CrossAccountId,450 _operator: T::CrossAccountId,451 _approve: bool,452 ) -> DispatchResultWithPostInfo {453 fail!(<Error<T>>::SettingAllowanceForAllNotAllowed)454 }455456 fn allowance_for_all(&self, _owner: T::CrossAccountId, _operator: T::CrossAccountId) -> bool {457 false458 }459460 /// Repairs a possibly broken item.461 fn repair_item(&self, _token: TokenId) -> DispatchResultWithPostInfo {462 fail!(<Error<T>>::FungibleTokensAreAlwaysValid)463 }464}pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -127,7 +127,7 @@
<SelfWeightOf<T>>::set_allowance_for_all()
}
- fn repair_item() -> Weight {
+ fn force_repair_item() -> Weight {
<SelfWeightOf<T>>::repair_item()
}
}
@@ -540,7 +540,7 @@
fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo {
with_weight(
<Pallet<T>>::repair_item(self, token),
- <CommonWeights<T>>::repair_item(),
+ <CommonWeights<T>>::force_repair_item(),
)
}
}
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -157,7 +157,7 @@
<SelfWeightOf<T>>::set_allowance_for_all()
}
- fn repair_item() -> Weight {
+ fn force_repair_item() -> Weight {
<SelfWeightOf<T>>::repair_item()
}
}
@@ -544,7 +544,7 @@
fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo {
with_weight(
<Pallet<T>>::repair_item(self, token),
- <CommonWeights<T>>::repair_item(),
+ <CommonWeights<T>>::force_repair_item(),
)
}
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -82,7 +82,7 @@
BoundedVec,
};
use scale_info::TypeInfo;
-use frame_system::{self as system, ensure_signed};
+use frame_system::{self as system, ensure_signed, ensure_root};
use sp_std::{vec, vec::Vec};
use up_data_structs::{
MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
@@ -983,18 +983,33 @@
})
}
- /// Repairs a broken item
+ /// Repairs a collection if the data was somehow corrupted.
///
/// # Arguments
///
+ /// * `collection_id`: ID of the collection to repair.
+ #[weight = <SelfWeightOf<T>>::force_repair_collection()]
+ pub fn force_repair_collection(
+ origin,
+ collection_id: CollectionId,
+ ) -> DispatchResult {
+ ensure_root(origin)?;
+ <PalletCommon<T>>::repair_collection(collection_id)
+ }
+
+ /// Repairs a token if the data was somehow corrupted.
+ ///
+ /// # Arguments
+ ///
/// * `collection_id`: ID of the collection the item belongs to.
/// * `item_id`: ID of the item.
- #[weight = T::CommonWeightInfo::repair_item()]
- pub fn repair_item(
- _origin,
+ #[weight = T::CommonWeightInfo::force_repair_item()]
+ pub fn force_repair_item(
+ origin,
collection_id: CollectionId,
item_id: TokenId,
) -> DispatchResultWithPostInfo {
+ ensure_root(origin)?;
dispatch_tx::<T, _>(collection_id, |d| {
d.repair_item(item_id)
})
pallets/unique/src/weights.rsdiffbeforeafterboth--- a/pallets/unique/src/weights.rs
+++ b/pallets/unique/src/weights.rs
@@ -45,6 +45,7 @@
fn remove_collection_sponsor() -> Weight;
fn set_transfers_enabled_flag() -> Weight;
fn set_collection_limits() -> Weight;
+ fn force_repair_collection() -> Weight;
}
/// Weights for pallet_unique using the Substrate node and recommended hardware.
@@ -139,6 +140,12 @@
.saturating_add(T::DbWeight::get().reads(1 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
+ // Storage: Common CollectionProperties (r:1 w:1)
+ fn force_repair_collection() -> Weight {
+ Weight::from_ref_time(5_701_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(1 as u64))
+ .saturating_add(T::DbWeight::get().writes(1 as u64))
+ }
}
// For backwards compatibility and tests
@@ -232,4 +239,10 @@
.saturating_add(RocksDbWeight::get().reads(1 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
+ // Storage: Common CollectionProperties (r:1 w:1)
+ fn force_repair_collection() -> Weight {
+ Weight::from_ref_time(5_701_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(1 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64))
+ }
}
runtime/common/weights.rsdiffbeforeafterboth--- a/runtime/common/weights.rs
+++ b/runtime/common/weights.rs
@@ -125,8 +125,8 @@
max_weight_of!(set_allowance_for_all())
}
- fn repair_item() -> Weight {
- max_weight_of!(repair_item())
+ fn force_repair_item() -> Weight {
+ max_weight_of!(force_repair_item())
}
}
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -44,8 +44,9 @@
"testEvmCoder": "mocha --timeout 9999999 -r ts-node/register './**/eth/evmCoder.test.ts'",
"testNesting": "mocha --timeout 9999999 -r ts-node/register ./**/nest.test.ts",
"testUnnesting": "mocha --timeout 9999999 -r ts-node/register ./**/unnest.test.ts",
- "testProperties": "mocha --timeout 9999999 -r ts-node/register ./**/collectionProperties.test.ts ./**/tokenProperties.test.ts ./**/getPropertiesRpc.test.ts",
- "testCollectionProperties": "mocha --timeout 9999999 -r ts-node/register ./**/collectionProperties.test.ts",
+ "testProperties": "mocha --timeout 9999999 -r ts-node/register ./**/collectionProperties.*test.ts ./**/tokenProperties.*test.ts ./**/getPropertiesRpc.test.ts",
+ "testCollectionProperties": "mocha --timeout 9999999 -r ts-node/register ./**/collectionProperties.*test.ts",
+ "testTokenProperties": "mocha --timeout 9999999 -r ts-node/register ./**/tokenProperties.*test.ts",
"testMigration": "mocha --timeout 9999999 -r ts-node/register ./**/nesting/migration-check.test.ts",
"testAddCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/addCollectionAdmin.test.ts",
"testSetCollectionLimits": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionLimits.test.ts",
tests/src/nesting/collectionProperties.seqtest.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/nesting/collectionProperties.seqtest.ts
@@ -0,0 +1,61 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+import {itSub, Pallets, usingPlaygrounds, expect, requirePalletsOrSkip} from '../util';
+
+describe('Integration Test: Collection Properties with sudo', () => {
+ let superuser: IKeyringPair;
+ let alice: IKeyringPair;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ superuser = await privateKey('//Alice');
+ const donor = await privateKey({filename: __filename});
+ [alice] = await helper.arrange.createAccounts([100n], donor);
+ });
+ });
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'ft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testSuite => describe(`${testSuite.mode.toUpperCase()}`, () => {
+ before(async function() {
+ // eslint-disable-next-line require-await
+ await usingPlaygrounds(async helper => {
+ requirePalletsOrSkip(this, helper, testSuite.requiredPallets);
+ });
+ });
+
+ itSub('Repairing an unbroken collection\'s properties preserves the consumed space', async({helper}) => {
+ const properties = [
+ {key: 'sea-creatures', value: 'mermaids'},
+ {key: 'goldenratio', value: '1.6180339887498948482045868343656381177203091798057628621354486227052604628189'},
+ ];
+ const collection = await helper[testSuite.mode].mintCollection(alice, {properties});
+
+ const newProperty = ' '.repeat(4096);
+ await collection.setProperties(alice, [{key: 'space', value: newProperty}]);
+ const originalSpace = await collection.getPropertiesConsumedSpace();
+ expect(originalSpace).to.be.equal(properties[0].value.length + properties[1].value.length + newProperty.length);
+
+ await helper.getSudo().executeExtrinsic(superuser, 'api.tx.unique.forceRepairCollection', [collection.collectionId], true);
+ const recomputedSpace = await collection.getPropertiesConsumedSpace();
+ expect(recomputedSpace).to.be.equal(originalSpace);
+ });
+ }));
+});
\ No newline at end of file
tests/src/nesting/collectionProperties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/collectionProperties.test.ts
+++ b/tests/src/nesting/collectionProperties.test.ts
@@ -314,6 +314,16 @@
).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
}
});
+
+ itSub('Forbids to repair a collection if called with non-sudo', async({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice, {properties: [
+ {key: 'sea-creatures', value: 'mermaids'},
+ {key: 'goldenratio', value: '1.6180339887498948482045868343656381177203091798057628621354486227052604628189'},
+ ]});
+
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.forceRepairCollection', [collection.collectionId], true))
+ .to.be.rejectedWith(/BadOrigin/);
+ });
}));
});
\ No newline at end of file
tests/src/nesting/tokenProperties.seqtest.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/nesting/tokenProperties.seqtest.ts
@@ -0,0 +1,72 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+import {itSub, Pallets, usingPlaygrounds, expect, requirePalletsOrSkip} from '../util';
+
+describe('Integration Test: Token Properties with sudo', () => {
+ let superuser: IKeyringPair;
+ let alice: IKeyringPair; // collection owner
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ superuser = await privateKey('//Alice');
+ const donor = await privateKey({filename: __filename});
+ [alice] = await helper.arrange.createAccounts([100n], donor);
+ });
+ });
+
+ [
+ {mode: 'nft' as const, pieces: undefined, requiredPallets: []},
+ {mode: 'rft' as const, pieces: 100n, requiredPallets: [Pallets.ReFungible]},
+ ].map(testSuite => describe(`${testSuite.mode.toUpperCase()}`, () => {
+ before(async function() {
+ // eslint-disable-next-line require-await
+ await usingPlaygrounds(async helper => {
+ requirePalletsOrSkip(this, helper, testSuite.requiredPallets);
+ });
+ });
+
+ itSub('force_repair_item preserves valid consumed space', async({helper}) => {
+ const propKey = 'tok-prop';
+
+ const collection = await helper[testSuite.mode].mintCollection(alice, {
+ tokenPropertyPermissions: [
+ {
+ key: propKey,
+ permission: {mutable: true, tokenOwner: true},
+ },
+ ],
+ });
+ const token = await (
+ testSuite.pieces
+ ? collection.mintToken(alice, testSuite.pieces)
+ : collection.mintToken(alice)
+ );
+
+ const propDataSize = 4096;
+ const propData = 'a'.repeat(propDataSize);
+
+ await token.setProperties(alice, [{key: propKey, value: propData}]);
+ const originalSpace = await token.getTokenPropertiesConsumedSpace();
+ expect(originalSpace).to.be.equal(propDataSize);
+
+ await helper.getSudo().executeExtrinsic(superuser, 'api.tx.unique.forceRepairItem', [token.collectionId, token.tokenId], true);
+ const recomputedSpace = await token.getTokenPropertiesConsumedSpace();
+ expect(recomputedSpace).to.be.equal(originalSpace);
+ });
+ }));
+});
\ No newline at end of file
tests/src/nesting/tokenProperties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/tokenProperties.test.ts
+++ b/tests/src/nesting/tokenProperties.test.ts
@@ -406,39 +406,6 @@
{mode: 'nft' as const, pieces: undefined, requiredPallets: []},
{mode: 'rft' as const, pieces: 100n, requiredPallets: [Pallets.ReFungible]},
].map(testCase =>
- itSub.ifWithPallets(`repair_item preserves valid consumed space (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
- const propKey = 'tok-prop';
-
- const collection = await helper[testCase.mode].mintCollection(alice, {
- tokenPropertyPermissions: [
- {
- key: propKey,
- permission: {mutable: true, tokenOwner: true},
- },
- ],
- });
- const token = await (
- testCase.pieces
- ? collection.mintToken(alice, testCase.pieces)
- : collection.mintToken(alice)
- );
-
- const propDataSize = 4096;
- const propData = 'a'.repeat(propDataSize);
-
- await token.setProperties(alice, [{key: propKey, value: propData}]);
- const originalSpace = await token.getTokenPropertiesConsumedSpace();
- expect(originalSpace).to.be.equal(propDataSize);
-
- await helper.executeExtrinsic(alice, 'api.tx.unique.repairItem', [token.collectionId, token.tokenId], true);
- const recomputedSpace = await token.getTokenPropertiesConsumedSpace();
- expect(recomputedSpace).to.be.equal(originalSpace);
- }));
-
- [
- {mode: 'nft' as const, pieces: undefined, requiredPallets: []},
- {mode: 'rft' as const, pieces: 100n, requiredPallets: [Pallets.ReFungible]},
- ].map(testCase =>
itSub.ifWithPallets(`Modifying a token property with different sizes correctly changes the consumed space (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
const propKey = 'tok-prop';
@@ -697,6 +664,35 @@
permission: {mutable: true, tokenOwner: true, collectionAdmin: true},
}])).to.be.rejectedWith(/common\.PropertyLimitReached/);
}));
+
+ [
+ {mode: 'nft' as const, pieces: undefined, requiredPallets: []},
+ {mode: 'rft' as const, pieces: 100n, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itSub.ifWithPallets(`Forbids force_repair_item from non-sudo (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
+ const propKey = 'tok-prop';
+
+ const collection = await helper[testCase.mode].mintCollection(alice, {
+ tokenPropertyPermissions: [
+ {
+ key: propKey,
+ permission: {mutable: true, tokenOwner: true},
+ },
+ ],
+ });
+ const token = await (
+ testCase.pieces
+ ? collection.mintToken(alice, testCase.pieces)
+ : collection.mintToken(alice)
+ );
+
+ const propDataSize = 4096;
+ const propData = 'a'.repeat(propDataSize);
+ await token.setProperties(alice, [{key: propKey, value: propData}]);
+
+ await expect(helper.executeExtrinsic(alice, 'api.tx.unique.forceRepairItem', [token.collectionId, token.tokenId], true))
+ .to.be.rejectedWith(/BadOrigin/);
+ }));
});
describe('ReFungible token properties permissions tests', () => {