difftreelog
feat(repair-item) change to force_repair_item + add force_repair_collection + tests
in: master
10 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -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.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -113,7 +113,7 @@
Weight::zero()
}
- fn repair_item() -> Weight {
+ fn force_repair_item() -> Weight {
Weight::zero()
}
}
pallets/nonfungible/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};20use up_data_structs::{21 TokenId, CreateItemExData, CollectionId, budget::Budget, Property, PropertyKey,22 PropertyKeyPermission, PropertyValue,23};24use pallet_common::{25 CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,26 weights::WeightInfo as _,27};28use sp_runtime::DispatchError;29use sp_std::{vec::Vec, vec};3031use crate::{32 AccountBalance, Allowance, Config, CreateItemData, Error, NonfungibleHandle, Owned, Pallet,33 SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted,34};3536pub struct CommonWeights<T: Config>(PhantomData<T>);37impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {38 fn create_item() -> Weight {39 <SelfWeightOf<T>>::create_item()40 }4142 fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {43 match data {44 CreateItemExData::NFT(t) => {45 <SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32)46 + t.iter()47 .filter_map(|t| {48 if t.properties.len() > 0 {49 Some(Self::set_token_properties(t.properties.len() as u32))50 } else {51 None52 }53 })54 .fold(Weight::zero(), |a, b| a.saturating_add(b))55 }56 _ => Weight::zero(),57 }58 }5960 fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {61 <SelfWeightOf<T>>::create_multiple_items(data.len() as u32)62 + data63 .iter()64 .filter_map(|t| match t {65 up_data_structs::CreateItemData::NFT(n) if n.properties.len() > 0 => {66 Some(Self::set_token_properties(n.properties.len() as u32))67 }68 _ => None,69 })70 .fold(Weight::zero(), |a, b| a.saturating_add(b))71 }7273 fn burn_item() -> Weight {74 <SelfWeightOf<T>>::burn_item()75 }7677 fn set_collection_properties(amount: u32) -> Weight {78 <pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)79 }8081 fn delete_collection_properties(amount: u32) -> Weight {82 <pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)83 }8485 fn set_token_properties(amount: u32) -> Weight {86 <SelfWeightOf<T>>::set_token_properties(amount)87 }8889 fn delete_token_properties(amount: u32) -> Weight {90 <SelfWeightOf<T>>::delete_token_properties(amount)91 }9293 fn set_token_property_permissions(amount: u32) -> Weight {94 <SelfWeightOf<T>>::set_token_property_permissions(amount)95 }9697 fn transfer() -> Weight {98 <SelfWeightOf<T>>::transfer()99 }100101 fn approve() -> Weight {102 <SelfWeightOf<T>>::approve()103 }104105 fn transfer_from() -> Weight {106 <SelfWeightOf<T>>::transfer_from()107 }108109 fn burn_from() -> Weight {110 <SelfWeightOf<T>>::burn_from()111 }112113 fn burn_recursively_self_raw() -> Weight {114 <SelfWeightOf<T>>::burn_recursively_self_raw()115 }116117 fn burn_recursively_breadth_raw(amount: u32) -> Weight {118 <SelfWeightOf<T>>::burn_recursively_breadth_plus_self_plus_self_per_each_raw(amount)119 .saturating_sub(Self::burn_recursively_self_raw().saturating_mul(amount as u64 + 1))120 }121122 fn token_owner() -> Weight {123 <SelfWeightOf<T>>::token_owner()124 }125126 fn set_allowance_for_all() -> Weight {127 <SelfWeightOf<T>>::set_allowance_for_all()128 }129130 fn repair_item() -> Weight {131 <SelfWeightOf<T>>::repair_item()132 }133}134135fn map_create_data<T: Config>(136 data: up_data_structs::CreateItemData,137 to: &T::CrossAccountId,138) -> Result<CreateItemData<T>, DispatchError> {139 match data {140 up_data_structs::CreateItemData::NFT(data) => Ok(CreateItemData::<T> {141 properties: data.properties,142 owner: to.clone(),143 }),144 _ => fail!(<Error<T>>::NotNonfungibleDataUsedToMintFungibleCollectionToken),145 }146}147148/// Implementation of `CommonCollectionOperations` for `NonfungibleHandle`. It wraps Nonfungible Pallete149/// methods and adds weight info.150impl<T: Config> CommonCollectionOperations<T> for NonfungibleHandle<T> {151 fn create_item(152 &self,153 sender: T::CrossAccountId,154 to: T::CrossAccountId,155 data: up_data_structs::CreateItemData,156 nesting_budget: &dyn Budget,157 ) -> DispatchResultWithPostInfo {158 with_weight(159 <Pallet<T>>::create_item(160 self,161 &sender,162 map_create_data::<T>(data, &to)?,163 nesting_budget,164 ),165 <CommonWeights<T>>::create_item(),166 )167 }168169 fn create_multiple_items(170 &self,171 sender: T::CrossAccountId,172 to: T::CrossAccountId,173 data: Vec<up_data_structs::CreateItemData>,174 nesting_budget: &dyn Budget,175 ) -> DispatchResultWithPostInfo {176 let weight = <CommonWeights<T>>::create_multiple_items(&data);177 let data = data178 .into_iter()179 .map(|d| map_create_data::<T>(d, &to))180 .collect::<Result<Vec<_>, DispatchError>>()?;181182 with_weight(183 <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),184 weight,185 )186 }187188 fn create_multiple_items_ex(189 &self,190 sender: <T>::CrossAccountId,191 data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,192 nesting_budget: &dyn Budget,193 ) -> DispatchResultWithPostInfo {194 let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);195 let data = match data {196 up_data_structs::CreateItemExData::NFT(nft) => nft,197 _ => fail!(Error::<T>::NotNonfungibleDataUsedToMintFungibleCollectionToken),198 };199200 with_weight(201 <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),202 weight,203 )204 }205206 fn set_collection_properties(207 &self,208 sender: T::CrossAccountId,209 properties: Vec<Property>,210 ) -> DispatchResultWithPostInfo {211 let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);212213 with_weight(214 <Pallet<T>>::set_collection_properties(self, &sender, properties),215 weight,216 )217 }218219 fn delete_collection_properties(220 &self,221 sender: &T::CrossAccountId,222 property_keys: Vec<PropertyKey>,223 ) -> DispatchResultWithPostInfo {224 let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);225226 with_weight(227 <Pallet<T>>::delete_collection_properties(self, sender, property_keys),228 weight,229 )230 }231232 fn set_token_properties(233 &self,234 sender: T::CrossAccountId,235 token_id: TokenId,236 properties: Vec<Property>,237 nesting_budget: &dyn Budget,238 ) -> DispatchResultWithPostInfo {239 let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);240241 with_weight(242 <Pallet<T>>::set_token_properties(243 self,244 &sender,245 token_id,246 properties.into_iter(),247 false,248 nesting_budget,249 ),250 weight,251 )252 }253254 fn delete_token_properties(255 &self,256 sender: T::CrossAccountId,257 token_id: TokenId,258 property_keys: Vec<PropertyKey>,259 nesting_budget: &dyn Budget,260 ) -> DispatchResultWithPostInfo {261 let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);262263 with_weight(264 <Pallet<T>>::delete_token_properties(265 self,266 &sender,267 token_id,268 property_keys.into_iter(),269 nesting_budget,270 ),271 weight,272 )273 }274275 fn set_token_property_permissions(276 &self,277 sender: &T::CrossAccountId,278 property_permissions: Vec<PropertyKeyPermission>,279 ) -> DispatchResultWithPostInfo {280 let weight =281 <CommonWeights<T>>::set_token_property_permissions(property_permissions.len() as u32);282283 with_weight(284 <Pallet<T>>::set_token_property_permissions(self, sender, property_permissions),285 weight,286 )287 }288289 fn burn_item(290 &self,291 sender: T::CrossAccountId,292 token: TokenId,293 amount: u128,294 ) -> DispatchResultWithPostInfo {295 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);296 if amount == 1 {297 with_weight(298 <Pallet<T>>::burn(self, &sender, token),299 <CommonWeights<T>>::burn_item(),300 )301 } else {302 <Pallet<T>>::check_token_immediate_ownership(self, token, &sender)?;303 Ok(().into())304 }305 }306307 fn burn_item_recursively(308 &self,309 sender: T::CrossAccountId,310 token: TokenId,311 self_budget: &dyn Budget,312 breadth_budget: &dyn Budget,313 ) -> DispatchResultWithPostInfo {314 <Pallet<T>>::burn_recursively(self, &sender, token, self_budget, breadth_budget)315 }316317 fn transfer(318 &self,319 from: T::CrossAccountId,320 to: T::CrossAccountId,321 token: TokenId,322 amount: u128,323 nesting_budget: &dyn Budget,324 ) -> DispatchResultWithPostInfo {325 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);326 if amount == 1 {327 with_weight(328 <Pallet<T>>::transfer(self, &from, &to, token, nesting_budget),329 <CommonWeights<T>>::transfer(),330 )331 } else {332 <Pallet<T>>::check_token_immediate_ownership(self, token, &from)?;333 Ok(().into())334 }335 }336337 fn approve(338 &self,339 sender: T::CrossAccountId,340 spender: T::CrossAccountId,341 token: TokenId,342 amount: u128,343 ) -> DispatchResultWithPostInfo {344 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);345346 with_weight(347 if amount == 1 {348 <Pallet<T>>::set_allowance(self, &sender, token, Some(&spender))349 } else {350 <Pallet<T>>::set_allowance(self, &sender, token, None)351 },352 <CommonWeights<T>>::approve(),353 )354 }355356 fn transfer_from(357 &self,358 sender: T::CrossAccountId,359 from: T::CrossAccountId,360 to: T::CrossAccountId,361 token: TokenId,362 amount: u128,363 nesting_budget: &dyn Budget,364 ) -> DispatchResultWithPostInfo {365 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);366367 if amount == 1 {368 with_weight(369 <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget),370 <CommonWeights<T>>::transfer_from(),371 )372 } else {373 <Pallet<T>>::check_allowed(self, &sender, &from, token, nesting_budget)?;374375 Ok(().into())376 }377 }378379 fn burn_from(380 &self,381 sender: T::CrossAccountId,382 from: T::CrossAccountId,383 token: TokenId,384 amount: u128,385 nesting_budget: &dyn Budget,386 ) -> DispatchResultWithPostInfo {387 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);388389 if amount == 1 {390 with_weight(391 <Pallet<T>>::burn_from(self, &sender, &from, token, nesting_budget),392 <CommonWeights<T>>::burn_from(),393 )394 } else {395 <Pallet<T>>::check_allowed(self, &sender, &from, token, nesting_budget)?;396397 Ok(().into())398 }399 }400401 fn check_nesting(402 &self,403 sender: T::CrossAccountId,404 from: (CollectionId, TokenId),405 under: TokenId,406 nesting_budget: &dyn Budget,407 ) -> sp_runtime::DispatchResult {408 <Pallet<T>>::check_nesting(self, sender, from, under, nesting_budget)409 }410411 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId)) {412 <Pallet<T>>::nest((self.id, under), to_nest);413 }414415 fn unnest(&self, under: TokenId, to_unnest: (CollectionId, TokenId)) {416 <Pallet<T>>::unnest((self.id, under), to_unnest);417 }418419 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {420 <Owned<T>>::iter_prefix((self.id, account))421 .map(|(id, _)| id)422 .collect()423 }424425 fn collection_tokens(&self) -> Vec<TokenId> {426 <TokenData<T>>::iter_prefix((self.id,))427 .map(|(id, _)| id)428 .collect()429 }430431 fn token_exists(&self, token: TokenId) -> bool {432 <Pallet<T>>::token_exists(self, token)433 }434435 fn last_token_id(&self) -> TokenId {436 TokenId(<TokensMinted<T>>::get(self.id))437 }438439 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {440 <TokenData<T>>::get((self.id, token)).map(|t| t.owner)441 }442443 /// Returns token owners.444 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {445 self.token_owner(token).map_or_else(|| vec![], |t| vec![t])446 }447448 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {449 <Pallet<T>>::token_properties((self.id, token_id))450 .get(key)451 .cloned()452 }453454 fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {455 let properties = <Pallet<T>>::token_properties((self.id, token_id));456457 keys.map(|keys| {458 keys.into_iter()459 .filter_map(|key| {460 properties.get(&key).map(|value| Property {461 key,462 value: value.clone(),463 })464 })465 .collect()466 })467 .unwrap_or_else(|| {468 properties469 .into_iter()470 .map(|(key, value)| Property { key, value })471 .collect()472 })473 }474475 fn total_supply(&self) -> u32 {476 <Pallet<T>>::total_supply(self)477 }478479 fn account_balance(&self, account: T::CrossAccountId) -> u32 {480 <AccountBalance<T>>::get((self.id, account))481 }482483 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {484 if <TokenData<T>>::get((self.id, token))485 .map(|a| a.owner == account)486 .unwrap_or(false)487 {488 1489 } else {490 0491 }492 }493494 fn allowance(495 &self,496 sender: T::CrossAccountId,497 spender: T::CrossAccountId,498 token: TokenId,499 ) -> u128 {500 if <TokenData<T>>::get((self.id, token))501 .map(|a| a.owner != sender)502 .unwrap_or(true)503 {504 0505 } else if <Allowance<T>>::get((self.id, token)) == Some(spender) {506 1507 } else {508 0509 }510 }511512 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {513 None514 }515516 fn total_pieces(&self, token: TokenId) -> Option<u128> {517 if <TokenData<T>>::contains_key((self.id, token)) {518 Some(1)519 } else {520 None521 }522 }523524 fn set_allowance_for_all(525 &self,526 owner: T::CrossAccountId,527 operator: T::CrossAccountId,528 approve: bool,529 ) -> DispatchResultWithPostInfo {530 with_weight(531 <Pallet<T>>::set_allowance_for_all(self, &owner, &operator, approve),532 <CommonWeights<T>>::set_allowance_for_all(),533 )534 }535536 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool {537 <Pallet<T>>::allowance_for_all(self, &owner, &operator)538 }539540 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo {541 with_weight(542 <Pallet<T>>::repair_item(self, token),543 <CommonWeights<T>>::repair_item(),544 )545 }546}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};20use up_data_structs::{21 TokenId, CreateItemExData, CollectionId, budget::Budget, Property, PropertyKey,22 PropertyKeyPermission, PropertyValue,23};24use pallet_common::{25 CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,26 weights::WeightInfo as _,27};28use sp_runtime::DispatchError;29use sp_std::{vec::Vec, vec};3031use crate::{32 AccountBalance, Allowance, Config, CreateItemData, Error, NonfungibleHandle, Owned, Pallet,33 SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted,34};3536pub struct CommonWeights<T: Config>(PhantomData<T>);37impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {38 fn create_item() -> Weight {39 <SelfWeightOf<T>>::create_item()40 }4142 fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {43 match data {44 CreateItemExData::NFT(t) => {45 <SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32)46 + t.iter()47 .filter_map(|t| {48 if t.properties.len() > 0 {49 Some(Self::set_token_properties(t.properties.len() as u32))50 } else {51 None52 }53 })54 .fold(Weight::zero(), |a, b| a.saturating_add(b))55 }56 _ => Weight::zero(),57 }58 }5960 fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {61 <SelfWeightOf<T>>::create_multiple_items(data.len() as u32)62 + data63 .iter()64 .filter_map(|t| match t {65 up_data_structs::CreateItemData::NFT(n) if n.properties.len() > 0 => {66 Some(Self::set_token_properties(n.properties.len() as u32))67 }68 _ => None,69 })70 .fold(Weight::zero(), |a, b| a.saturating_add(b))71 }7273 fn burn_item() -> Weight {74 <SelfWeightOf<T>>::burn_item()75 }7677 fn set_collection_properties(amount: u32) -> Weight {78 <pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)79 }8081 fn delete_collection_properties(amount: u32) -> Weight {82 <pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)83 }8485 fn set_token_properties(amount: u32) -> Weight {86 <SelfWeightOf<T>>::set_token_properties(amount)87 }8889 fn delete_token_properties(amount: u32) -> Weight {90 <SelfWeightOf<T>>::delete_token_properties(amount)91 }9293 fn set_token_property_permissions(amount: u32) -> Weight {94 <SelfWeightOf<T>>::set_token_property_permissions(amount)95 }9697 fn transfer() -> Weight {98 <SelfWeightOf<T>>::transfer()99 }100101 fn approve() -> Weight {102 <SelfWeightOf<T>>::approve()103 }104105 fn transfer_from() -> Weight {106 <SelfWeightOf<T>>::transfer_from()107 }108109 fn burn_from() -> Weight {110 <SelfWeightOf<T>>::burn_from()111 }112113 fn burn_recursively_self_raw() -> Weight {114 <SelfWeightOf<T>>::burn_recursively_self_raw()115 }116117 fn burn_recursively_breadth_raw(amount: u32) -> Weight {118 <SelfWeightOf<T>>::burn_recursively_breadth_plus_self_plus_self_per_each_raw(amount)119 .saturating_sub(Self::burn_recursively_self_raw().saturating_mul(amount as u64 + 1))120 }121122 fn token_owner() -> Weight {123 <SelfWeightOf<T>>::token_owner()124 }125126 fn set_allowance_for_all() -> Weight {127 <SelfWeightOf<T>>::set_allowance_for_all()128 }129130 fn force_repair_item() -> Weight {131 <SelfWeightOf<T>>::repair_item()132 }133}134135fn map_create_data<T: Config>(136 data: up_data_structs::CreateItemData,137 to: &T::CrossAccountId,138) -> Result<CreateItemData<T>, DispatchError> {139 match data {140 up_data_structs::CreateItemData::NFT(data) => Ok(CreateItemData::<T> {141 properties: data.properties,142 owner: to.clone(),143 }),144 _ => fail!(<Error<T>>::NotNonfungibleDataUsedToMintFungibleCollectionToken),145 }146}147148/// Implementation of `CommonCollectionOperations` for `NonfungibleHandle`. It wraps Nonfungible Pallete149/// methods and adds weight info.150impl<T: Config> CommonCollectionOperations<T> for NonfungibleHandle<T> {151 fn create_item(152 &self,153 sender: T::CrossAccountId,154 to: T::CrossAccountId,155 data: up_data_structs::CreateItemData,156 nesting_budget: &dyn Budget,157 ) -> DispatchResultWithPostInfo {158 with_weight(159 <Pallet<T>>::create_item(160 self,161 &sender,162 map_create_data::<T>(data, &to)?,163 nesting_budget,164 ),165 <CommonWeights<T>>::create_item(),166 )167 }168169 fn create_multiple_items(170 &self,171 sender: T::CrossAccountId,172 to: T::CrossAccountId,173 data: Vec<up_data_structs::CreateItemData>,174 nesting_budget: &dyn Budget,175 ) -> DispatchResultWithPostInfo {176 let weight = <CommonWeights<T>>::create_multiple_items(&data);177 let data = data178 .into_iter()179 .map(|d| map_create_data::<T>(d, &to))180 .collect::<Result<Vec<_>, DispatchError>>()?;181182 with_weight(183 <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),184 weight,185 )186 }187188 fn create_multiple_items_ex(189 &self,190 sender: <T>::CrossAccountId,191 data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,192 nesting_budget: &dyn Budget,193 ) -> DispatchResultWithPostInfo {194 let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);195 let data = match data {196 up_data_structs::CreateItemExData::NFT(nft) => nft,197 _ => fail!(Error::<T>::NotNonfungibleDataUsedToMintFungibleCollectionToken),198 };199200 with_weight(201 <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),202 weight,203 )204 }205206 fn set_collection_properties(207 &self,208 sender: T::CrossAccountId,209 properties: Vec<Property>,210 ) -> DispatchResultWithPostInfo {211 let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);212213 with_weight(214 <Pallet<T>>::set_collection_properties(self, &sender, properties),215 weight,216 )217 }218219 fn delete_collection_properties(220 &self,221 sender: &T::CrossAccountId,222 property_keys: Vec<PropertyKey>,223 ) -> DispatchResultWithPostInfo {224 let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);225226 with_weight(227 <Pallet<T>>::delete_collection_properties(self, sender, property_keys),228 weight,229 )230 }231232 fn set_token_properties(233 &self,234 sender: T::CrossAccountId,235 token_id: TokenId,236 properties: Vec<Property>,237 nesting_budget: &dyn Budget,238 ) -> DispatchResultWithPostInfo {239 let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);240241 with_weight(242 <Pallet<T>>::set_token_properties(243 self,244 &sender,245 token_id,246 properties.into_iter(),247 false,248 nesting_budget,249 ),250 weight,251 )252 }253254 fn delete_token_properties(255 &self,256 sender: T::CrossAccountId,257 token_id: TokenId,258 property_keys: Vec<PropertyKey>,259 nesting_budget: &dyn Budget,260 ) -> DispatchResultWithPostInfo {261 let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);262263 with_weight(264 <Pallet<T>>::delete_token_properties(265 self,266 &sender,267 token_id,268 property_keys.into_iter(),269 nesting_budget,270 ),271 weight,272 )273 }274275 fn set_token_property_permissions(276 &self,277 sender: &T::CrossAccountId,278 property_permissions: Vec<PropertyKeyPermission>,279 ) -> DispatchResultWithPostInfo {280 let weight =281 <CommonWeights<T>>::set_token_property_permissions(property_permissions.len() as u32);282283 with_weight(284 <Pallet<T>>::set_token_property_permissions(self, sender, property_permissions),285 weight,286 )287 }288289 fn burn_item(290 &self,291 sender: T::CrossAccountId,292 token: TokenId,293 amount: u128,294 ) -> DispatchResultWithPostInfo {295 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);296 if amount == 1 {297 with_weight(298 <Pallet<T>>::burn(self, &sender, token),299 <CommonWeights<T>>::burn_item(),300 )301 } else {302 <Pallet<T>>::check_token_immediate_ownership(self, token, &sender)?;303 Ok(().into())304 }305 }306307 fn burn_item_recursively(308 &self,309 sender: T::CrossAccountId,310 token: TokenId,311 self_budget: &dyn Budget,312 breadth_budget: &dyn Budget,313 ) -> DispatchResultWithPostInfo {314 <Pallet<T>>::burn_recursively(self, &sender, token, self_budget, breadth_budget)315 }316317 fn transfer(318 &self,319 from: T::CrossAccountId,320 to: T::CrossAccountId,321 token: TokenId,322 amount: u128,323 nesting_budget: &dyn Budget,324 ) -> DispatchResultWithPostInfo {325 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);326 if amount == 1 {327 with_weight(328 <Pallet<T>>::transfer(self, &from, &to, token, nesting_budget),329 <CommonWeights<T>>::transfer(),330 )331 } else {332 <Pallet<T>>::check_token_immediate_ownership(self, token, &from)?;333 Ok(().into())334 }335 }336337 fn approve(338 &self,339 sender: T::CrossAccountId,340 spender: T::CrossAccountId,341 token: TokenId,342 amount: u128,343 ) -> DispatchResultWithPostInfo {344 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);345346 with_weight(347 if amount == 1 {348 <Pallet<T>>::set_allowance(self, &sender, token, Some(&spender))349 } else {350 <Pallet<T>>::set_allowance(self, &sender, token, None)351 },352 <CommonWeights<T>>::approve(),353 )354 }355356 fn transfer_from(357 &self,358 sender: T::CrossAccountId,359 from: T::CrossAccountId,360 to: T::CrossAccountId,361 token: TokenId,362 amount: u128,363 nesting_budget: &dyn Budget,364 ) -> DispatchResultWithPostInfo {365 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);366367 if amount == 1 {368 with_weight(369 <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget),370 <CommonWeights<T>>::transfer_from(),371 )372 } else {373 <Pallet<T>>::check_allowed(self, &sender, &from, token, nesting_budget)?;374375 Ok(().into())376 }377 }378379 fn burn_from(380 &self,381 sender: T::CrossAccountId,382 from: T::CrossAccountId,383 token: TokenId,384 amount: u128,385 nesting_budget: &dyn Budget,386 ) -> DispatchResultWithPostInfo {387 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);388389 if amount == 1 {390 with_weight(391 <Pallet<T>>::burn_from(self, &sender, &from, token, nesting_budget),392 <CommonWeights<T>>::burn_from(),393 )394 } else {395 <Pallet<T>>::check_allowed(self, &sender, &from, token, nesting_budget)?;396397 Ok(().into())398 }399 }400401 fn check_nesting(402 &self,403 sender: T::CrossAccountId,404 from: (CollectionId, TokenId),405 under: TokenId,406 nesting_budget: &dyn Budget,407 ) -> sp_runtime::DispatchResult {408 <Pallet<T>>::check_nesting(self, sender, from, under, nesting_budget)409 }410411 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId)) {412 <Pallet<T>>::nest((self.id, under), to_nest);413 }414415 fn unnest(&self, under: TokenId, to_unnest: (CollectionId, TokenId)) {416 <Pallet<T>>::unnest((self.id, under), to_unnest);417 }418419 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {420 <Owned<T>>::iter_prefix((self.id, account))421 .map(|(id, _)| id)422 .collect()423 }424425 fn collection_tokens(&self) -> Vec<TokenId> {426 <TokenData<T>>::iter_prefix((self.id,))427 .map(|(id, _)| id)428 .collect()429 }430431 fn token_exists(&self, token: TokenId) -> bool {432 <Pallet<T>>::token_exists(self, token)433 }434435 fn last_token_id(&self) -> TokenId {436 TokenId(<TokensMinted<T>>::get(self.id))437 }438439 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {440 <TokenData<T>>::get((self.id, token)).map(|t| t.owner)441 }442443 /// Returns token owners.444 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {445 self.token_owner(token).map_or_else(|| vec![], |t| vec![t])446 }447448 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {449 <Pallet<T>>::token_properties((self.id, token_id))450 .get(key)451 .cloned()452 }453454 fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {455 let properties = <Pallet<T>>::token_properties((self.id, token_id));456457 keys.map(|keys| {458 keys.into_iter()459 .filter_map(|key| {460 properties.get(&key).map(|value| Property {461 key,462 value: value.clone(),463 })464 })465 .collect()466 })467 .unwrap_or_else(|| {468 properties469 .into_iter()470 .map(|(key, value)| Property { key, value })471 .collect()472 })473 }474475 fn total_supply(&self) -> u32 {476 <Pallet<T>>::total_supply(self)477 }478479 fn account_balance(&self, account: T::CrossAccountId) -> u32 {480 <AccountBalance<T>>::get((self.id, account))481 }482483 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {484 if <TokenData<T>>::get((self.id, token))485 .map(|a| a.owner == account)486 .unwrap_or(false)487 {488 1489 } else {490 0491 }492 }493494 fn allowance(495 &self,496 sender: T::CrossAccountId,497 spender: T::CrossAccountId,498 token: TokenId,499 ) -> u128 {500 if <TokenData<T>>::get((self.id, token))501 .map(|a| a.owner != sender)502 .unwrap_or(true)503 {504 0505 } else if <Allowance<T>>::get((self.id, token)) == Some(spender) {506 1507 } else {508 0509 }510 }511512 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {513 None514 }515516 fn total_pieces(&self, token: TokenId) -> Option<u128> {517 if <TokenData<T>>::contains_key((self.id, token)) {518 Some(1)519 } else {520 None521 }522 }523524 fn set_allowance_for_all(525 &self,526 owner: T::CrossAccountId,527 operator: T::CrossAccountId,528 approve: bool,529 ) -> DispatchResultWithPostInfo {530 with_weight(531 <Pallet<T>>::set_allowance_for_all(self, &owner, &operator, approve),532 <CommonWeights<T>>::set_allowance_for_all(),533 )534 }535536 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool {537 <Pallet<T>>::allowance_for_all(self, &owner, &operator)538 }539540 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo {541 with_weight(542 <Pallet<T>>::repair_item(self, token),543 <CommonWeights<T>>::force_repair_item(),544 )545 }546}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's properties 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's properties 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
@@ -46,6 +46,7 @@
"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",
+ "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.test.tsdiffbeforeafterboth--- a/tests/src/nesting/collectionProperties.test.ts
+++ b/tests/src/nesting/collectionProperties.test.ts
@@ -18,11 +18,13 @@
import {itSub, Pallets, usingPlaygrounds, expect, requirePalletsOrSkip} from '../util';
describe('Integration Test: Collection Properties', () => {
+ let superuser: IKeyringPair;
let alice: IKeyringPair;
let bob: IKeyringPair;
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
+ superuser = await privateKey('//Alice');
const donor = await privateKey({filename: __filename});
[alice, bob] = await helper.arrange.createAccounts([200n, 10n], donor);
});
@@ -199,6 +201,23 @@
expectedConsumedSpaceDiff = biggerPropDataSize - smallerPropDataSize;
expect(consumedSpace).to.be.equal(biggerPropDataSize - expectedConsumedSpaceDiff);
});
+
+ itSub('Modifying a collection property with different sizes correctly changes 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);
+ });
}));
});
@@ -314,6 +333,16 @@
).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
}
});
+
+ itSub('Modifying a collection property with different sizes correctly changes the consumed space', 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.test.tsdiffbeforeafterboth--- a/tests/src/nesting/tokenProperties.test.ts
+++ b/tests/src/nesting/tokenProperties.test.ts
@@ -19,6 +19,7 @@
import {UniqueHelper, UniqueNFToken, UniqueRFToken} from '../util/playgrounds/unique';
describe('Integration Test: Token Properties', () => {
+ let superuser: IKeyringPair;
let alice: IKeyringPair; // collection owner
let bob: IKeyringPair; // collection admin
let charlie: IKeyringPair; // token owner
@@ -27,6 +28,7 @@
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
+ superuser = await privateKey('//Alice');
const donor = await privateKey({filename: __filename});
[alice, bob, charlie] = await helper.arrange.createAccounts([200n, 100n, 100n], donor);
});
@@ -406,7 +408,7 @@
{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}) => {
+ itSub.ifWithPallets(`force_repair_item preserves valid consumed space (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
const propKey = 'tok-prop';
const collection = await helper[testCase.mode].mintCollection(alice, {
@@ -430,7 +432,7 @@
const originalSpace = await token.getTokenPropertiesConsumedSpace();
expect(originalSpace).to.be.equal(propDataSize);
- await helper.executeExtrinsic(alice, 'api.tx.unique.repairItem', [token.collectionId, token.tokenId], true);
+ 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);
}));
@@ -697,6 +699,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', () => {