difftreelog
fieat: add repair_item extrinsic + test
in: master
15 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -1815,6 +1815,9 @@
/// The price of setting approval for all
fn set_allowance_for_all() -> Weight;
+
+ /// The price of repairing an item.
+ fn repair_item() -> Weight;
}
/// Weight info extension trait for refungible pallet.
@@ -2136,6 +2139,9 @@
/// Tells whether the given `owner` approves the `operator`.
fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;
+
+ /// Repairs a possibly broken item.
+ fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;
}
/// Extension for RFT collection.
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::{CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight};22use pallet_structure::Error as StructureError;23use sp_runtime::ArithmeticError;24use sp_std::{vec::Vec, vec};25use up_data_structs::{Property, PropertyKey, PropertyValue, PropertyKeyPermission};2627use crate::{28 Allowance, TotalSupply, Balance, Config, Error, FungibleHandle, Pallet, SelfWeightOf,29 weights::WeightInfo,30};3132pub struct CommonWeights<T: Config>(PhantomData<T>);33impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {34 fn create_item() -> Weight {35 <SelfWeightOf<T>>::create_item()36 }3738 fn create_multiple_items(_data: &[CreateItemData]) -> Weight {39 // All items minted for the same user, so it works same as create_item40 Self::create_item()41 }4243 fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {44 match data {45 CreateItemExData::Fungible(f) => {46 <SelfWeightOf<T>>::create_multiple_items_ex(f.len() as u32)47 }48 _ => Weight::zero(),49 }50 }5152 fn burn_item() -> Weight {53 <SelfWeightOf<T>>::burn_item()54 }5556 fn set_collection_properties(_amount: u32) -> Weight {57 // Error58 Weight::zero()59 }6061 fn delete_collection_properties(_amount: u32) -> Weight {62 // Error63 Weight::zero()64 }6566 fn set_token_properties(_amount: u32) -> Weight {67 // Error68 Weight::zero()69 }7071 fn delete_token_properties(_amount: u32) -> Weight {72 // Error73 Weight::zero()74 }7576 fn set_token_property_permissions(_amount: u32) -> Weight {77 // Error78 Weight::zero()79 }8081 fn transfer() -> Weight {82 <SelfWeightOf<T>>::transfer()83 }8485 fn approve() -> Weight {86 <SelfWeightOf<T>>::approve()87 }8889 fn transfer_from() -> Weight {90 <SelfWeightOf<T>>::transfer_from()91 }9293 fn burn_from() -> Weight {94 <SelfWeightOf<T>>::burn_from()95 }9697 fn burn_recursively_self_raw() -> Weight {98 // Read to get total balance99 Self::burn_item() + T::DbWeight::get().reads(1)100 }101102 fn burn_recursively_breadth_raw(_amount: u32) -> Weight {103 // Fungible tokens can't have children104 Weight::zero()105 }106107 fn token_owner() -> Weight {108 Weight::zero()109 }110111 fn set_allowance_for_all() -> Weight {112 Weight::zero()113 }114}115116/// Implementation of `CommonCollectionOperations` for `FungibleHandle`. It wraps FungibleHandle Pallete117/// methods and adds weight info.118impl<T: Config> CommonCollectionOperations<T> for FungibleHandle<T> {119 fn create_item(120 &self,121 sender: T::CrossAccountId,122 to: T::CrossAccountId,123 data: up_data_structs::CreateItemData,124 nesting_budget: &dyn Budget,125 ) -> DispatchResultWithPostInfo {126 match data {127 up_data_structs::CreateItemData::Fungible(data) => with_weight(128 <Pallet<T>>::create_item(self, &sender, (to, data.value), nesting_budget),129 <CommonWeights<T>>::create_item(),130 ),131 _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),132 }133 }134135 fn create_multiple_items(136 &self,137 sender: T::CrossAccountId,138 to: T::CrossAccountId,139 data: Vec<up_data_structs::CreateItemData>,140 nesting_budget: &dyn Budget,141 ) -> DispatchResultWithPostInfo {142 let mut sum: u128 = 0;143 for data in data {144 match data {145 up_data_structs::CreateItemData::Fungible(data) => {146 sum = sum147 .checked_add(data.value)148 .ok_or(ArithmeticError::Overflow)?;149 }150 _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),151 }152 }153154 with_weight(155 <Pallet<T>>::create_item(self, &sender, (to, sum), nesting_budget),156 <CommonWeights<T>>::create_item(),157 )158 }159160 fn create_multiple_items_ex(161 &self,162 sender: <T>::CrossAccountId,163 data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,164 nesting_budget: &dyn Budget,165 ) -> DispatchResultWithPostInfo {166 let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);167 let data = match data {168 up_data_structs::CreateItemExData::Fungible(f) => f,169 _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),170 };171172 with_weight(173 <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),174 weight,175 )176 }177178 fn burn_item(179 &self,180 sender: T::CrossAccountId,181 token: TokenId,182 amount: u128,183 ) -> DispatchResultWithPostInfo {184 ensure!(185 token == TokenId::default(),186 <Error<T>>::FungibleItemsHaveNoId187 );188189 with_weight(190 <Pallet<T>>::burn(self, &sender, amount),191 <CommonWeights<T>>::burn_item(),192 )193 }194195 fn burn_item_recursively(196 &self,197 sender: T::CrossAccountId,198 token: TokenId,199 self_budget: &dyn Budget,200 _breadth_budget: &dyn Budget,201 ) -> DispatchResultWithPostInfo {202 // Should not happen?203 ensure!(204 token == TokenId::default(),205 <Error<T>>::FungibleItemsHaveNoId206 );207 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);208209 with_weight(210 <Pallet<T>>::burn(self, &sender, <Balance<T>>::get((self.id, &sender))),211 <CommonWeights<T>>::burn_recursively_self_raw(),212 )213 }214215 fn transfer(216 &self,217 from: T::CrossAccountId,218 to: T::CrossAccountId,219 token: TokenId,220 amount: u128,221 nesting_budget: &dyn Budget,222 ) -> DispatchResultWithPostInfo {223 ensure!(224 token == TokenId::default(),225 <Error<T>>::FungibleItemsHaveNoId226 );227228 with_weight(229 <Pallet<T>>::transfer(self, &from, &to, amount, nesting_budget),230 <CommonWeights<T>>::transfer(),231 )232 }233234 fn approve(235 &self,236 sender: T::CrossAccountId,237 spender: T::CrossAccountId,238 token: TokenId,239 amount: u128,240 ) -> DispatchResultWithPostInfo {241 ensure!(242 token == TokenId::default(),243 <Error<T>>::FungibleItemsHaveNoId244 );245246 with_weight(247 <Pallet<T>>::set_allowance(self, &sender, &spender, amount),248 <CommonWeights<T>>::approve(),249 )250 }251252 fn transfer_from(253 &self,254 sender: T::CrossAccountId,255 from: T::CrossAccountId,256 to: T::CrossAccountId,257 token: TokenId,258 amount: u128,259 nesting_budget: &dyn Budget,260 ) -> DispatchResultWithPostInfo {261 ensure!(262 token == TokenId::default(),263 <Error<T>>::FungibleItemsHaveNoId264 );265266 with_weight(267 <Pallet<T>>::transfer_from(self, &sender, &from, &to, amount, nesting_budget),268 <CommonWeights<T>>::transfer_from(),269 )270 }271272 fn burn_from(273 &self,274 sender: T::CrossAccountId,275 from: T::CrossAccountId,276 token: TokenId,277 amount: u128,278 nesting_budget: &dyn Budget,279 ) -> DispatchResultWithPostInfo {280 ensure!(281 token == TokenId::default(),282 <Error<T>>::FungibleItemsHaveNoId283 );284285 with_weight(286 <Pallet<T>>::burn_from(self, &sender, &from, amount, nesting_budget),287 <CommonWeights<T>>::burn_from(),288 )289 }290291 fn set_collection_properties(292 &self,293 _sender: T::CrossAccountId,294 _property: Vec<Property>,295 ) -> DispatchResultWithPostInfo {296 fail!(<Error<T>>::SettingPropertiesNotAllowed)297 }298299 fn delete_collection_properties(300 &self,301 _sender: &T::CrossAccountId,302 _property_keys: Vec<PropertyKey>,303 ) -> DispatchResultWithPostInfo {304 fail!(<Error<T>>::SettingPropertiesNotAllowed)305 }306307 fn set_token_properties(308 &self,309 _sender: T::CrossAccountId,310 _token_id: TokenId,311 _property: Vec<Property>,312 _nesting_budget: &dyn Budget,313 ) -> DispatchResultWithPostInfo {314 fail!(<Error<T>>::SettingPropertiesNotAllowed)315 }316317 fn set_token_property_permissions(318 &self,319 _sender: &T::CrossAccountId,320 _property_permissions: Vec<PropertyKeyPermission>,321 ) -> DispatchResultWithPostInfo {322 fail!(<Error<T>>::SettingPropertiesNotAllowed)323 }324325 fn delete_token_properties(326 &self,327 _sender: T::CrossAccountId,328 _token_id: TokenId,329 _property_keys: Vec<PropertyKey>,330 _nesting_budget: &dyn Budget,331 ) -> DispatchResultWithPostInfo {332 fail!(<Error<T>>::SettingPropertiesNotAllowed)333 }334335 fn check_nesting(336 &self,337 _sender: <T>::CrossAccountId,338 _from: (CollectionId, TokenId),339 _under: TokenId,340 _nesting_budget: &dyn Budget,341 ) -> sp_runtime::DispatchResult {342 fail!(<Error<T>>::FungibleDisallowsNesting)343 }344345 fn nest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}346347 fn unnest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}348349 fn collection_tokens(&self) -> Vec<TokenId> {350 vec![TokenId::default()]351 }352353 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {354 if <Balance<T>>::get((self.id, account)) != 0 {355 vec![TokenId::default()]356 } else {357 vec![]358 }359 }360361 fn token_exists(&self, token: TokenId) -> bool {362 token == TokenId::default()363 }364365 fn last_token_id(&self) -> TokenId {366 TokenId::default()367 }368369 fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {370 None371 }372373 /// Returns 10 tokens owners in no particular order.374 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {375 <Pallet<T>>::token_owners(self.id, token).unwrap_or_default()376 }377378 fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {379 None380 }381382 fn token_properties(383 &self,384 _token_id: TokenId,385 _keys: Option<Vec<PropertyKey>>,386 ) -> Vec<Property> {387 Vec::new()388 }389390 fn total_supply(&self) -> u32 {391 1392 }393394 fn account_balance(&self, account: T::CrossAccountId) -> u32 {395 if <Balance<T>>::get((self.id, account)) != 0 {396 1397 } else {398 0399 }400 }401402 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {403 if token != TokenId::default() {404 return 0;405 }406 <Balance<T>>::get((self.id, account))407 }408409 fn allowance(410 &self,411 sender: T::CrossAccountId,412 spender: T::CrossAccountId,413 token: TokenId,414 ) -> u128 {415 if token != TokenId::default() {416 return 0;417 }418 <Allowance<T>>::get((self.id, sender, spender))419 }420421 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {422 None423 }424425 fn total_pieces(&self, token: TokenId) -> Option<u128> {426 if token != TokenId::default() {427 return None;428 }429 <TotalSupply<T>>::try_get(self.id).ok()430 }431432 fn set_allowance_for_all(433 &self,434 _owner: T::CrossAccountId,435 _operator: T::CrossAccountId,436 _approve: bool,437 ) -> DispatchResultWithPostInfo {438 fail!(<Error<T>>::SettingAllowanceForAllNotAllowed)439 }440441 fn allowance_for_all(&self, _owner: T::CrossAccountId, _operator: T::CrossAccountId) -> bool {442 false443 }444}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::{CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight};22use pallet_structure::Error as StructureError;23use sp_runtime::ArithmeticError;24use sp_std::{vec::Vec, vec};25use up_data_structs::{Property, PropertyKey, PropertyValue, PropertyKeyPermission};2627use crate::{28 Allowance, TotalSupply, Balance, Config, Error, FungibleHandle, Pallet, SelfWeightOf,29 weights::WeightInfo,30};3132pub struct CommonWeights<T: Config>(PhantomData<T>);33impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {34 fn create_item() -> Weight {35 <SelfWeightOf<T>>::create_item()36 }3738 fn create_multiple_items(_data: &[CreateItemData]) -> Weight {39 // All items minted for the same user, so it works same as create_item40 Self::create_item()41 }4243 fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {44 match data {45 CreateItemExData::Fungible(f) => {46 <SelfWeightOf<T>>::create_multiple_items_ex(f.len() as u32)47 }48 _ => Weight::zero(),49 }50 }5152 fn burn_item() -> Weight {53 <SelfWeightOf<T>>::burn_item()54 }5556 fn set_collection_properties(_amount: u32) -> Weight {57 // Error58 Weight::zero()59 }6061 fn delete_collection_properties(_amount: u32) -> Weight {62 // Error63 Weight::zero()64 }6566 fn set_token_properties(_amount: u32) -> Weight {67 // Error68 Weight::zero()69 }7071 fn delete_token_properties(_amount: u32) -> Weight {72 // Error73 Weight::zero()74 }7576 fn set_token_property_permissions(_amount: u32) -> Weight {77 // Error78 Weight::zero()79 }8081 fn transfer() -> Weight {82 <SelfWeightOf<T>>::transfer()83 }8485 fn approve() -> Weight {86 <SelfWeightOf<T>>::approve()87 }8889 fn transfer_from() -> Weight {90 <SelfWeightOf<T>>::transfer_from()91 }9293 fn burn_from() -> Weight {94 <SelfWeightOf<T>>::burn_from()95 }9697 fn burn_recursively_self_raw() -> Weight {98 // Read to get total balance99 Self::burn_item() + T::DbWeight::get().reads(1)100 }101102 fn burn_recursively_breadth_raw(_amount: u32) -> Weight {103 // Fungible tokens can't have children104 Weight::zero()105 }106107 fn token_owner() -> Weight {108 Weight::zero()109 }110111 fn set_allowance_for_all() -> Weight {112 Weight::zero()113 }114115 fn repair_item() -> Weight {116 Weight::zero()117 }118}119120/// Implementation of `CommonCollectionOperations` for `FungibleHandle`. It wraps FungibleHandle Pallete121/// methods and adds weight info.122impl<T: Config> CommonCollectionOperations<T> for FungibleHandle<T> {123 fn create_item(124 &self,125 sender: T::CrossAccountId,126 to: T::CrossAccountId,127 data: up_data_structs::CreateItemData,128 nesting_budget: &dyn Budget,129 ) -> DispatchResultWithPostInfo {130 match data {131 up_data_structs::CreateItemData::Fungible(data) => with_weight(132 <Pallet<T>>::create_item(self, &sender, (to, data.value), nesting_budget),133 <CommonWeights<T>>::create_item(),134 ),135 _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),136 }137 }138139 fn create_multiple_items(140 &self,141 sender: T::CrossAccountId,142 to: T::CrossAccountId,143 data: Vec<up_data_structs::CreateItemData>,144 nesting_budget: &dyn Budget,145 ) -> DispatchResultWithPostInfo {146 let mut sum: u128 = 0;147 for data in data {148 match data {149 up_data_structs::CreateItemData::Fungible(data) => {150 sum = sum151 .checked_add(data.value)152 .ok_or(ArithmeticError::Overflow)?;153 }154 _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),155 }156 }157158 with_weight(159 <Pallet<T>>::create_item(self, &sender, (to, sum), nesting_budget),160 <CommonWeights<T>>::create_item(),161 )162 }163164 fn create_multiple_items_ex(165 &self,166 sender: <T>::CrossAccountId,167 data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,168 nesting_budget: &dyn Budget,169 ) -> DispatchResultWithPostInfo {170 let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);171 let data = match data {172 up_data_structs::CreateItemExData::Fungible(f) => f,173 _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),174 };175176 with_weight(177 <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),178 weight,179 )180 }181182 fn burn_item(183 &self,184 sender: T::CrossAccountId,185 token: TokenId,186 amount: u128,187 ) -> DispatchResultWithPostInfo {188 ensure!(189 token == TokenId::default(),190 <Error<T>>::FungibleItemsHaveNoId191 );192193 with_weight(194 <Pallet<T>>::burn(self, &sender, amount),195 <CommonWeights<T>>::burn_item(),196 )197 }198199 fn burn_item_recursively(200 &self,201 sender: T::CrossAccountId,202 token: TokenId,203 self_budget: &dyn Budget,204 _breadth_budget: &dyn Budget,205 ) -> DispatchResultWithPostInfo {206 // Should not happen?207 ensure!(208 token == TokenId::default(),209 <Error<T>>::FungibleItemsHaveNoId210 );211 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);212213 with_weight(214 <Pallet<T>>::burn(self, &sender, <Balance<T>>::get((self.id, &sender))),215 <CommonWeights<T>>::burn_recursively_self_raw(),216 )217 }218219 fn transfer(220 &self,221 from: T::CrossAccountId,222 to: T::CrossAccountId,223 token: TokenId,224 amount: u128,225 nesting_budget: &dyn Budget,226 ) -> DispatchResultWithPostInfo {227 ensure!(228 token == TokenId::default(),229 <Error<T>>::FungibleItemsHaveNoId230 );231232 with_weight(233 <Pallet<T>>::transfer(self, &from, &to, amount, nesting_budget),234 <CommonWeights<T>>::transfer(),235 )236 }237238 fn approve(239 &self,240 sender: T::CrossAccountId,241 spender: T::CrossAccountId,242 token: TokenId,243 amount: u128,244 ) -> DispatchResultWithPostInfo {245 ensure!(246 token == TokenId::default(),247 <Error<T>>::FungibleItemsHaveNoId248 );249250 with_weight(251 <Pallet<T>>::set_allowance(self, &sender, &spender, amount),252 <CommonWeights<T>>::approve(),253 )254 }255256 fn transfer_from(257 &self,258 sender: T::CrossAccountId,259 from: T::CrossAccountId,260 to: T::CrossAccountId,261 token: TokenId,262 amount: u128,263 nesting_budget: &dyn Budget,264 ) -> DispatchResultWithPostInfo {265 ensure!(266 token == TokenId::default(),267 <Error<T>>::FungibleItemsHaveNoId268 );269270 with_weight(271 <Pallet<T>>::transfer_from(self, &sender, &from, &to, amount, nesting_budget),272 <CommonWeights<T>>::transfer_from(),273 )274 }275276 fn burn_from(277 &self,278 sender: T::CrossAccountId,279 from: T::CrossAccountId,280 token: TokenId,281 amount: u128,282 nesting_budget: &dyn Budget,283 ) -> DispatchResultWithPostInfo {284 ensure!(285 token == TokenId::default(),286 <Error<T>>::FungibleItemsHaveNoId287 );288289 with_weight(290 <Pallet<T>>::burn_from(self, &sender, &from, amount, nesting_budget),291 <CommonWeights<T>>::burn_from(),292 )293 }294295 fn set_collection_properties(296 &self,297 _sender: T::CrossAccountId,298 _property: Vec<Property>,299 ) -> DispatchResultWithPostInfo {300 fail!(<Error<T>>::SettingPropertiesNotAllowed)301 }302303 fn delete_collection_properties(304 &self,305 _sender: &T::CrossAccountId,306 _property_keys: Vec<PropertyKey>,307 ) -> DispatchResultWithPostInfo {308 fail!(<Error<T>>::SettingPropertiesNotAllowed)309 }310311 fn set_token_properties(312 &self,313 _sender: T::CrossAccountId,314 _token_id: TokenId,315 _property: Vec<Property>,316 _nesting_budget: &dyn Budget,317 ) -> DispatchResultWithPostInfo {318 fail!(<Error<T>>::SettingPropertiesNotAllowed)319 }320321 fn set_token_property_permissions(322 &self,323 _sender: &T::CrossAccountId,324 _property_permissions: Vec<PropertyKeyPermission>,325 ) -> DispatchResultWithPostInfo {326 fail!(<Error<T>>::SettingPropertiesNotAllowed)327 }328329 fn delete_token_properties(330 &self,331 _sender: T::CrossAccountId,332 _token_id: TokenId,333 _property_keys: Vec<PropertyKey>,334 _nesting_budget: &dyn Budget,335 ) -> DispatchResultWithPostInfo {336 fail!(<Error<T>>::SettingPropertiesNotAllowed)337 }338339 fn check_nesting(340 &self,341 _sender: <T>::CrossAccountId,342 _from: (CollectionId, TokenId),343 _under: TokenId,344 _nesting_budget: &dyn Budget,345 ) -> sp_runtime::DispatchResult {346 fail!(<Error<T>>::FungibleDisallowsNesting)347 }348349 fn nest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}350351 fn unnest(&self, _under: TokenId, _to_nest: (CollectionId, TokenId)) {}352353 fn collection_tokens(&self) -> Vec<TokenId> {354 vec![TokenId::default()]355 }356357 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {358 if <Balance<T>>::get((self.id, account)) != 0 {359 vec![TokenId::default()]360 } else {361 vec![]362 }363 }364365 fn token_exists(&self, token: TokenId) -> bool {366 token == TokenId::default()367 }368369 fn last_token_id(&self) -> TokenId {370 TokenId::default()371 }372373 fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {374 None375 }376377 /// Returns 10 tokens owners in no particular order.378 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {379 <Pallet<T>>::token_owners(self.id, token).unwrap_or_default()380 }381382 fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {383 None384 }385386 fn token_properties(387 &self,388 _token_id: TokenId,389 _keys: Option<Vec<PropertyKey>>,390 ) -> Vec<Property> {391 Vec::new()392 }393394 fn total_supply(&self) -> u32 {395 1396 }397398 fn account_balance(&self, account: T::CrossAccountId) -> u32 {399 if <Balance<T>>::get((self.id, account)) != 0 {400 1401 } else {402 0403 }404 }405406 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {407 if token != TokenId::default() {408 return 0;409 }410 <Balance<T>>::get((self.id, account))411 }412413 fn allowance(414 &self,415 sender: T::CrossAccountId,416 spender: T::CrossAccountId,417 token: TokenId,418 ) -> u128 {419 if token != TokenId::default() {420 return 0;421 }422 <Allowance<T>>::get((self.id, sender, spender))423 }424425 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {426 None427 }428429 fn total_pieces(&self, token: TokenId) -> Option<u128> {430 if token != TokenId::default() {431 return None;432 }433 <TotalSupply<T>>::try_get(self.id).ok()434 }435436 fn set_allowance_for_all(437 &self,438 _owner: T::CrossAccountId,439 _operator: T::CrossAccountId,440 _approve: bool,441 ) -> DispatchResultWithPostInfo {442 fail!(<Error<T>>::SettingAllowanceForAllNotAllowed)443 }444445 fn allowance_for_all(&self, _owner: T::CrossAccountId, _operator: T::CrossAccountId) -> bool {446 false447 }448449 /// Repairs a possibly broken item.450 fn repair_item(&self, _token: TokenId) -> DispatchResultWithPostInfo {451 fail!(<Error<T>>::FungibleTokensAreAlwaysValid)452 }453}pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -129,6 +129,8 @@
SettingPropertiesNotAllowed,
/// Setting allowance for all is not allowed.
SettingAllowanceForAllNotAllowed,
+ /// Only a fungible collection could be possibly broken; any fungible token is valid.
+ FungibleTokensAreAlwaysValid,
}
#[pallet::config]
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -236,4 +236,12 @@
operator: cross_sub;
};
}: {<Pallet<T>>::allowance_for_all(&collection, &owner, &operator)}
+
+ repair_item {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub;
+ };
+ let item = create_max_item(&collection, &owner, owner.clone())?;
+ }: {<Pallet<T>>::repair_item(&collection, item)?}
}
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -126,6 +126,10 @@
fn set_allowance_for_all() -> Weight {
<SelfWeightOf<T>>::set_allowance_for_all()
}
+
+ fn repair_item() -> Weight {
+ <SelfWeightOf<T>>::repair_item()
+ }
}
fn map_create_data<T: Config>(
@@ -532,4 +536,11 @@
fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool {
<Pallet<T>>::allowance_for_all(self, &owner, &operator)
}
+
+ fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo {
+ with_weight(
+ <Pallet<T>>::repair_item(self, token),
+ <CommonWeights<T>>::repair_item(),
+ )
+ }
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -1398,4 +1398,12 @@
) -> bool {
<CollectionAllowance<T>>::get((collection.id, owner, operator))
}
+
+ pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {
+ <TokenProperties<T>>::mutate((collection.id, token), |properties| {
+ properties.recompute_consumed_space();
+ });
+
+ Ok(())
+ }
}
pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -50,6 +50,7 @@
fn token_owner() -> Weight;
fn set_allowance_for_all() -> Weight;
fn allowance_for_all() -> Weight;
+ fn repair_item() -> Weight;
}
/// Weights for pallet_nonfungible using the Substrate node and recommended hardware.
@@ -208,6 +209,12 @@
Weight::from_ref_time(6_161_000 as u64)
.saturating_add(T::DbWeight::get().reads(1 as u64))
}
+ // Storage: Nonfungible TokenProperties (r:1 w:1)
+ fn repair_item() -> 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
@@ -365,4 +372,10 @@
Weight::from_ref_time(6_161_000 as u64)
.saturating_add(RocksDbWeight::get().reads(1 as u64))
}
+ // Storage: Nonfungible TokenProperties (r:1 w:1)
+ fn repair_item() -> 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))
+ }
}
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -304,4 +304,12 @@
operator: cross_sub;
};
}: {<Pallet<T>>::allowance_for_all(&collection, &owner, &operator)}
+
+ repair_item {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub;
+ };
+ let item = create_max_item(&collection, &owner, [(owner.clone(), 100)])?;
+ }: {<Pallet<T>>::repair_item(&collection, item)?}
}
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -156,6 +156,10 @@
fn set_allowance_for_all() -> Weight {
<SelfWeightOf<T>>::set_allowance_for_all()
}
+
+ fn repair_item() -> Weight {
+ <SelfWeightOf<T>>::repair_item()
+ }
}
fn map_create_data<T: Config>(
@@ -536,6 +540,13 @@
fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool {
<Pallet<T>>::allowance_for_all(self, &owner, &operator)
}
+
+ fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo {
+ with_weight(
+ <Pallet<T>>::repair_item(self, token),
+ <CommonWeights<T>>::repair_item(),
+ )
+ }
}
impl<T: Config> RefungibleExtensions<T> for RefungibleHandle<T> {
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -1461,4 +1461,12 @@
) -> bool {
<CollectionAllowance<T>>::get((collection.id, owner, operator))
}
+
+ pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {
+ <TokenProperties<T>>::mutate((collection.id, token), |properties| {
+ properties.recompute_consumed_space();
+ });
+
+ Ok(())
+ }
}
pallets/refungible/src/weights.rsdiffbeforeafterboth--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -57,6 +57,7 @@
fn token_owner() -> Weight;
fn set_allowance_for_all() -> Weight;
fn allowance_for_all() -> Weight;
+ fn repair_item() -> Weight;
}
/// Weights for pallet_refungible using the Substrate node and recommended hardware.
@@ -272,6 +273,12 @@
Weight::from_ref_time(5_901_000 as u64)
.saturating_add(T::DbWeight::get().reads(1 as u64))
}
+ // Storage: Refungible TokenProperties (r:1 w:1)
+ fn repair_item() -> Weight {
+ Weight::from_ref_time(5_489_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
@@ -486,4 +493,10 @@
Weight::from_ref_time(5_901_000 as u64)
.saturating_add(RocksDbWeight::get().reads(1 as u64))
}
+ // Storage: Refungible TokenProperties (r:1 w:1)
+ fn repair_item() -> Weight {
+ Weight::from_ref_time(5_489_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(1 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64))
+ }
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -982,6 +982,23 @@
d.set_allowance_for_all(sender, operator, approve)
})
}
+
+ /// Repairs a broken item
+ ///
+ /// # 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,
+ collection_id: CollectionId,
+ item_id: TokenId,
+ ) -> DispatchResultWithPostInfo {
+ dispatch_tx::<T, _>(collection_id, |d| {
+ d.repair_item(item_id)
+ })
+ }
}
}
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -1218,6 +1218,10 @@
Ok(())
}
+
+ pub fn values(&self) -> impl Iterator<Item = &Value> {
+ self.0.values()
+ }
}
impl<Value> IntoIterator for PropertiesMap<Value> {
@@ -1290,6 +1294,12 @@
pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {
self.map.get(key)
}
+
+ /// Recomputes the consumed space for the current properties state.
+ /// Needed to repair a token due to a bug fixed in the [PR #733](https://github.com/UniqueNetwork/unique-chain/pull/773).
+ pub fn recompute_consumed_space(&mut self) {
+ self.consumed_space = self.map.values().map(|value| value.len() as u32).sum();
+ }
}
impl IntoIterator for Properties {
runtime/common/weights.rsdiffbeforeafterboth--- a/runtime/common/weights.rs
+++ b/runtime/common/weights.rs
@@ -124,6 +124,10 @@
fn set_allowance_for_all() -> Weight {
max_weight_of!(set_allowance_for_all())
}
+
+ fn repair_item() -> Weight {
+ max_weight_of!(repair_item())
+ }
}
#[cfg(feature = "refungible")]
tests/src/nesting/tokenProperties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/tokenProperties.test.ts
+++ b/tests/src/nesting/tokenProperties.test.ts
@@ -28,7 +28,7 @@
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ [alice, bob, charlie] = await helper.arrange.createAccounts([200n, 100n, 100n], donor);
});
permissions = [
@@ -401,6 +401,39 @@
consumedSpace = await token.getTokenPropertiesConsumedSpace();
expect(consumedSpace).to.be.equal(originalSpace);
}));
+
+ [
+ {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);
+ }));
});
describe('Negative Integration Test: Token Properties', () => {