difftreelog
Merge pull request #773 from UniqueNetwork/fix/properties-size-overflow
in: master
Fix/properties size overflow
18 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.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -111,6 +111,10 @@
fn set_allowance_for_all() -> Weight {
Weight::zero()
}
+
+ fn repair_item() -> Weight {
+ Weight::zero()
+ }
}
/// Implementation of `CommonCollectionOperations` for `FungibleHandle`. It wraps FungibleHandle Pallete
@@ -441,4 +445,9 @@
fn allowance_for_all(&self, _owner: T::CrossAccountId, _operator: T::CrossAccountId) -> bool {
false
}
+
+ /// Repairs a possibly broken item.
+ fn repair_item(&self, _token: TokenId) -> DispatchResultWithPostInfo {
+ fail!(<Error<T>>::FungibleTokensAreAlwaysValid)
+ }
}
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.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 }129}130131fn map_create_data<T: Config>(132 data: up_data_structs::CreateItemData,133 to: &T::CrossAccountId,134) -> Result<CreateItemData<T>, DispatchError> {135 match data {136 up_data_structs::CreateItemData::NFT(data) => Ok(CreateItemData::<T> {137 properties: data.properties,138 owner: to.clone(),139 }),140 _ => fail!(<Error<T>>::NotNonfungibleDataUsedToMintFungibleCollectionToken),141 }142}143144/// Implementation of `CommonCollectionOperations` for `NonfungibleHandle`. It wraps Nonfungible Pallete145/// methods and adds weight info.146impl<T: Config> CommonCollectionOperations<T> for NonfungibleHandle<T> {147 fn create_item(148 &self,149 sender: T::CrossAccountId,150 to: T::CrossAccountId,151 data: up_data_structs::CreateItemData,152 nesting_budget: &dyn Budget,153 ) -> DispatchResultWithPostInfo {154 with_weight(155 <Pallet<T>>::create_item(156 self,157 &sender,158 map_create_data::<T>(data, &to)?,159 nesting_budget,160 ),161 <CommonWeights<T>>::create_item(),162 )163 }164165 fn create_multiple_items(166 &self,167 sender: T::CrossAccountId,168 to: T::CrossAccountId,169 data: Vec<up_data_structs::CreateItemData>,170 nesting_budget: &dyn Budget,171 ) -> DispatchResultWithPostInfo {172 let weight = <CommonWeights<T>>::create_multiple_items(&data);173 let data = data174 .into_iter()175 .map(|d| map_create_data::<T>(d, &to))176 .collect::<Result<Vec<_>, DispatchError>>()?;177178 with_weight(179 <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),180 weight,181 )182 }183184 fn create_multiple_items_ex(185 &self,186 sender: <T>::CrossAccountId,187 data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,188 nesting_budget: &dyn Budget,189 ) -> DispatchResultWithPostInfo {190 let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);191 let data = match data {192 up_data_structs::CreateItemExData::NFT(nft) => nft,193 _ => fail!(Error::<T>::NotNonfungibleDataUsedToMintFungibleCollectionToken),194 };195196 with_weight(197 <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),198 weight,199 )200 }201202 fn set_collection_properties(203 &self,204 sender: T::CrossAccountId,205 properties: Vec<Property>,206 ) -> DispatchResultWithPostInfo {207 let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);208209 with_weight(210 <Pallet<T>>::set_collection_properties(self, &sender, properties),211 weight,212 )213 }214215 fn delete_collection_properties(216 &self,217 sender: &T::CrossAccountId,218 property_keys: Vec<PropertyKey>,219 ) -> DispatchResultWithPostInfo {220 let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);221222 with_weight(223 <Pallet<T>>::delete_collection_properties(self, sender, property_keys),224 weight,225 )226 }227228 fn set_token_properties(229 &self,230 sender: T::CrossAccountId,231 token_id: TokenId,232 properties: Vec<Property>,233 nesting_budget: &dyn Budget,234 ) -> DispatchResultWithPostInfo {235 let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);236237 with_weight(238 <Pallet<T>>::set_token_properties(239 self,240 &sender,241 token_id,242 properties.into_iter(),243 false,244 nesting_budget,245 ),246 weight,247 )248 }249250 fn delete_token_properties(251 &self,252 sender: T::CrossAccountId,253 token_id: TokenId,254 property_keys: Vec<PropertyKey>,255 nesting_budget: &dyn Budget,256 ) -> DispatchResultWithPostInfo {257 let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);258259 with_weight(260 <Pallet<T>>::delete_token_properties(261 self,262 &sender,263 token_id,264 property_keys.into_iter(),265 nesting_budget,266 ),267 weight,268 )269 }270271 fn set_token_property_permissions(272 &self,273 sender: &T::CrossAccountId,274 property_permissions: Vec<PropertyKeyPermission>,275 ) -> DispatchResultWithPostInfo {276 let weight =277 <CommonWeights<T>>::set_token_property_permissions(property_permissions.len() as u32);278279 with_weight(280 <Pallet<T>>::set_token_property_permissions(self, sender, property_permissions),281 weight,282 )283 }284285 fn burn_item(286 &self,287 sender: T::CrossAccountId,288 token: TokenId,289 amount: u128,290 ) -> DispatchResultWithPostInfo {291 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);292 if amount == 1 {293 with_weight(294 <Pallet<T>>::burn(self, &sender, token),295 <CommonWeights<T>>::burn_item(),296 )297 } else {298 <Pallet<T>>::check_token_immediate_ownership(self, token, &sender)?;299 Ok(().into())300 }301 }302303 fn burn_item_recursively(304 &self,305 sender: T::CrossAccountId,306 token: TokenId,307 self_budget: &dyn Budget,308 breadth_budget: &dyn Budget,309 ) -> DispatchResultWithPostInfo {310 <Pallet<T>>::burn_recursively(self, &sender, token, self_budget, breadth_budget)311 }312313 fn transfer(314 &self,315 from: T::CrossAccountId,316 to: T::CrossAccountId,317 token: TokenId,318 amount: u128,319 nesting_budget: &dyn Budget,320 ) -> DispatchResultWithPostInfo {321 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);322 if amount == 1 {323 with_weight(324 <Pallet<T>>::transfer(self, &from, &to, token, nesting_budget),325 <CommonWeights<T>>::transfer(),326 )327 } else {328 <Pallet<T>>::check_token_immediate_ownership(self, token, &from)?;329 Ok(().into())330 }331 }332333 fn approve(334 &self,335 sender: T::CrossAccountId,336 spender: T::CrossAccountId,337 token: TokenId,338 amount: u128,339 ) -> DispatchResultWithPostInfo {340 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);341342 with_weight(343 if amount == 1 {344 <Pallet<T>>::set_allowance(self, &sender, token, Some(&spender))345 } else {346 <Pallet<T>>::set_allowance(self, &sender, token, None)347 },348 <CommonWeights<T>>::approve(),349 )350 }351352 fn transfer_from(353 &self,354 sender: T::CrossAccountId,355 from: T::CrossAccountId,356 to: T::CrossAccountId,357 token: TokenId,358 amount: u128,359 nesting_budget: &dyn Budget,360 ) -> DispatchResultWithPostInfo {361 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);362363 if amount == 1 {364 with_weight(365 <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget),366 <CommonWeights<T>>::transfer_from(),367 )368 } else {369 <Pallet<T>>::check_allowed(self, &sender, &from, token, nesting_budget)?;370371 Ok(().into())372 }373 }374375 fn burn_from(376 &self,377 sender: T::CrossAccountId,378 from: T::CrossAccountId,379 token: TokenId,380 amount: u128,381 nesting_budget: &dyn Budget,382 ) -> DispatchResultWithPostInfo {383 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);384385 if amount == 1 {386 with_weight(387 <Pallet<T>>::burn_from(self, &sender, &from, token, nesting_budget),388 <CommonWeights<T>>::burn_from(),389 )390 } else {391 <Pallet<T>>::check_allowed(self, &sender, &from, token, nesting_budget)?;392393 Ok(().into())394 }395 }396397 fn check_nesting(398 &self,399 sender: T::CrossAccountId,400 from: (CollectionId, TokenId),401 under: TokenId,402 nesting_budget: &dyn Budget,403 ) -> sp_runtime::DispatchResult {404 <Pallet<T>>::check_nesting(self, sender, from, under, nesting_budget)405 }406407 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId)) {408 <Pallet<T>>::nest((self.id, under), to_nest);409 }410411 fn unnest(&self, under: TokenId, to_unnest: (CollectionId, TokenId)) {412 <Pallet<T>>::unnest((self.id, under), to_unnest);413 }414415 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {416 <Owned<T>>::iter_prefix((self.id, account))417 .map(|(id, _)| id)418 .collect()419 }420421 fn collection_tokens(&self) -> Vec<TokenId> {422 <TokenData<T>>::iter_prefix((self.id,))423 .map(|(id, _)| id)424 .collect()425 }426427 fn token_exists(&self, token: TokenId) -> bool {428 <Pallet<T>>::token_exists(self, token)429 }430431 fn last_token_id(&self) -> TokenId {432 TokenId(<TokensMinted<T>>::get(self.id))433 }434435 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {436 <TokenData<T>>::get((self.id, token)).map(|t| t.owner)437 }438439 /// Returns token owners.440 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {441 self.token_owner(token).map_or_else(|| vec![], |t| vec![t])442 }443444 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {445 <Pallet<T>>::token_properties((self.id, token_id))446 .get(key)447 .cloned()448 }449450 fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {451 let properties = <Pallet<T>>::token_properties((self.id, token_id));452453 keys.map(|keys| {454 keys.into_iter()455 .filter_map(|key| {456 properties.get(&key).map(|value| Property {457 key,458 value: value.clone(),459 })460 })461 .collect()462 })463 .unwrap_or_else(|| {464 properties465 .into_iter()466 .map(|(key, value)| Property { key, value })467 .collect()468 })469 }470471 fn total_supply(&self) -> u32 {472 <Pallet<T>>::total_supply(self)473 }474475 fn account_balance(&self, account: T::CrossAccountId) -> u32 {476 <AccountBalance<T>>::get((self.id, account))477 }478479 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {480 if <TokenData<T>>::get((self.id, token))481 .map(|a| a.owner == account)482 .unwrap_or(false)483 {484 1485 } else {486 0487 }488 }489490 fn allowance(491 &self,492 sender: T::CrossAccountId,493 spender: T::CrossAccountId,494 token: TokenId,495 ) -> u128 {496 if <TokenData<T>>::get((self.id, token))497 .map(|a| a.owner != sender)498 .unwrap_or(true)499 {500 0501 } else if <Allowance<T>>::get((self.id, token)) == Some(spender) {502 1503 } else {504 0505 }506 }507508 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {509 None510 }511512 fn total_pieces(&self, token: TokenId) -> Option<u128> {513 if <TokenData<T>>::contains_key((self.id, token)) {514 Some(1)515 } else {516 None517 }518 }519520 fn set_allowance_for_all(521 &self,522 owner: T::CrossAccountId,523 operator: T::CrossAccountId,524 approve: bool,525 ) -> DispatchResultWithPostInfo {526 with_weight(527 <Pallet<T>>::set_allowance_for_all(self, &owner, &operator, approve),528 <CommonWeights<T>>::set_allowance_for_all(),529 )530 }531532 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool {533 <Pallet<T>>::allowance_for_all(self, &owner, &operator)534 }535}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 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}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
@@ -1133,7 +1133,7 @@
scope: PropertyScope,
key: PropertyKey,
value: Self::Value,
- ) -> Result<(), PropertiesError>;
+ ) -> Result<Option<Self::Value>, PropertiesError>;
/// Try to set property with scope from iterator.
fn try_scoped_set_from_iter<I, KV>(
@@ -1154,7 +1154,11 @@
}
/// Try to set property.
- fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {
+ fn try_set(
+ &mut self,
+ key: PropertyKey,
+ value: Self::Value,
+ ) -> Result<Option<Self::Value>, PropertiesError> {
self.try_scoped_set(PropertyScope::None, key, value)
}
@@ -1214,6 +1218,10 @@
Ok(())
}
+
+ pub fn values(&self) -> impl Iterator<Item = &Value> {
+ self.0.values()
+ }
}
impl<Value> IntoIterator for PropertiesMap<Value> {
@@ -1239,15 +1247,13 @@
scope: PropertyScope,
key: PropertyKey,
value: Self::Value,
- ) -> Result<(), PropertiesError> {
+ ) -> Result<Option<Self::Value>, PropertiesError> {
Self::check_property_key(&key)?;
let key = scope.apply(key)?;
self.0
.try_insert(key, value)
- .map_err(|_| PropertiesError::PropertyLimitReached)?;
-
- Ok(())
+ .map_err(|_| PropertiesError::PropertyLimitReached)
}
}
@@ -1288,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 {
@@ -1307,7 +1319,7 @@
scope: PropertyScope,
key: PropertyKey,
value: Self::Value,
- ) -> Result<(), PropertiesError> {
+ ) -> Result<Option<Self::Value>, PropertiesError> {
let value_len = value.len();
if self.consumed_space as usize + value_len > self.space_limit as usize
@@ -1316,11 +1328,13 @@
return Err(PropertiesError::NoSpaceForProperty);
}
- self.map.try_scoped_set(scope, key, value)?;
+ let old_value = self.map.try_scoped_set(scope, key, value)?;
- self.consumed_space += value_len as u32;
+ if old_value.is_none() {
+ self.consumed_space += value_len as u32;
+ }
- Ok(())
+ Ok(old_value)
}
}
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/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -41,11 +41,10 @@
"testEvent": "yarn setup && mocha --timeout 9999999 -r ts-node/register ./src/check-event/*.*test.ts",
"testRmrk": "yarn setup && mocha --timeout 9999999 -r ts-node/register ./**/rmrk/*.*test.ts",
"testEthPayable": "mocha --timeout 9999999 -r ts-node/register './**/eth/payable.test.ts'",
- "testEthTokenProperties": "mocha --timeout 9999999 -r ts-node/register ./**/eth/tokenProperties.test.ts",
"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 ./**/properties.test.ts ./**/getPropertiesRpc.test.ts",
+ "testProperties": "mocha --timeout 9999999 -r ts-node/register ./**/collectionProperties.test.ts ./**/tokenProperties.test.ts ./**/getPropertiesRpc.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
@@ -25,7 +25,7 @@
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
const donor = await privateKey({filename: __filename});
- [alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);
+ [alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);
});
});
@@ -131,6 +131,66 @@
itSub.ifWithPallets('Deletes properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
await testDeleteProperties(await helper.rft.mintCollection(alice));
});
+
+ [
+ // TODO enable properties for FT collection in Substrate (release 040)
+ // {mode: 'ft' as const, requiredPallets: []},
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itSub.ifWithPallets(`Allows modifying a collection property multiple times (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
+ const propKey = 'tok-prop';
+
+ const collection = await helper[testCase.mode].mintCollection(alice);
+
+ const maxCollectionPropertiesSize = 40960;
+
+ const propDataSize = 4096;
+
+ let propDataChar = 'a';
+ const makeNewPropData = () => {
+ propDataChar = String.fromCharCode(propDataChar.charCodeAt(0) + 1);
+ return `${propDataChar}`.repeat(propDataSize);
+ };
+
+ await collection.setProperties(alice, [{key: propKey, value: makeNewPropData()}]);
+ const originalSpace = await collection.getPropertiesConsumedSpace();
+ expect(originalSpace).to.be.equal(propDataSize);
+
+ const sameSizePropertiesPossibleNum = maxCollectionPropertiesSize / propDataSize;
+
+ // It is possible to modify a property as many times as needed.
+ // It will not consume any additional space.
+ for (let i = 0; i < sameSizePropertiesPossibleNum + 1; i++) {
+ await collection.setProperties(alice, [{key: propKey, value: makeNewPropData()}]);
+ const consumedSpace = await collection.getPropertiesConsumedSpace();
+ expect(consumedSpace).to.be.equal(originalSpace);
+ }
+ }));
+
+ [
+ // TODO enable properties for FT collection in Substrate (release 040)
+ // {mode: 'ft' as const, requiredPallets: []},
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itSub.ifWithPallets(`Adding then removing a collection property doesn't change the consumed space (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
+ const propKey = 'tok-prop';
+
+ const collection = await helper[testCase.mode].mintCollection(alice);
+ const originalSpace = await collection.getPropertiesConsumedSpace();
+
+ const propDataSize = 4096;
+ const propData = 'a'.repeat(propDataSize);
+
+ await collection.setProperties(alice, [{key: propKey, value: propData}]);
+ let consumedSpace = await collection.getPropertiesConsumedSpace();
+ expect(consumedSpace).to.be.equal(propDataSize);
+
+ await collection.deleteProperties(alice, [propKey]);
+ consumedSpace = await collection.getPropertiesConsumedSpace();
+ expect(consumedSpace).to.be.equal(originalSpace);
+ }));
});
describe('Negative Integration Test: Collection Properties', () => {
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 = [
@@ -320,6 +320,120 @@
expect((await nestedToken.getData())!.properties).to.be.empty;
expect(await targetToken.getProperties()).to.be.empty;
});
+
+ [
+ {mode: 'nft' as const, storage: 'nonfungible' as const, pieces: undefined, requiredPallets: []},
+ {mode: 'rft' as const, storage: 'refungible' as const, pieces: 100n, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itSub.ifWithPallets(`Allows modifying a token property multiple times (${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 maxTokenPropertiesSize = 32768;
+
+ const propDataSize = 4096;
+
+ let propDataChar = 'a';
+ const makeNewPropData = () => {
+ propDataChar = String.fromCharCode(propDataChar.charCodeAt(0) + 1);
+ return `${propDataChar}`.repeat(propDataSize);
+ };
+
+ const token = await (
+ testCase.pieces
+ ? collection.mintToken(alice, testCase.pieces)
+ : collection.mintToken(alice)
+ );
+
+ await token.setProperties(alice, [{key: propKey, value: makeNewPropData()}]);
+ const originalSpace = await token.getTokenPropertiesConsumedSpace();
+ expect(originalSpace).to.be.equal(propDataSize);
+
+ const sameSizePropertiesPossibleNum = maxTokenPropertiesSize / propDataSize;
+
+ // It is possible to modify a property as many times as needed.
+ // It will not consume any additional space.
+ for (let i = 0; i < sameSizePropertiesPossibleNum + 1; i++) {
+ await token.setProperties(alice, [{key: propKey, value: makeNewPropData()}]);
+ const 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(`Adding then removing a token property doesn't change the 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 originalSpace = await token.getTokenPropertiesConsumedSpace();
+
+ const propDataSize = 4096;
+ const propData = 'a'.repeat(propDataSize);
+
+ await token.setProperties(alice, [{key: propKey, value: propData}]);
+ let consumedSpace = await token.getTokenPropertiesConsumedSpace();
+ expect(consumedSpace).to.be.equal(propDataSize);
+
+ await token.deleteProperties(alice, [propKey]);
+ 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', () => {
@@ -476,7 +590,7 @@
await testForbidsAddingPropertiesIfPropertyNotDeclared(token, amount);
});
- async function testForbidsAddingTooManyProperties(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {
+ async function testForbidsAddingTooLargeProperties(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {
const originalSpace = await prepare(token, pieces);
await expect(
@@ -504,15 +618,36 @@
expect(consumedSpace).to.be.equal(originalSpace);
}
- itSub('Forbids adding too many properties to a token (NFT)', async ({helper}) => {
+ itSub('Forbids adding too large properties to a token (NFT)', async ({helper}) => {
const [token, amount] = await mintCollectionWithAllPermissionsAndToken(helper, 'NFT');
- await testForbidsAddingTooManyProperties(token, amount);
+ await testForbidsAddingTooLargeProperties(token, amount);
});
- itSub.ifWithPallets('Forbids adding too many properties to a token (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
+ itSub.ifWithPallets('Forbids adding too large properties to a token (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
const [token, amount] = await mintCollectionWithAllPermissionsAndToken(helper, 'RFT');
- await testForbidsAddingTooManyProperties(token, amount);
+ await testForbidsAddingTooLargeProperties(token, amount);
});
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itSub.ifWithPallets(`Forbids adding too many propeties to a token (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
+ const collection = await helper[testCase.mode].mintCollection(alice);
+ const maxPropertiesPerItem = 64;
+
+ for (let i = 0; i < maxPropertiesPerItem; i++) {
+ await collection.setTokenPropertyPermissions(alice, [{
+ key: `${i+1}`,
+ permission: {mutable: true, tokenOwner: true, collectionAdmin: true},
+ }]);
+ }
+
+ await expect(collection.setTokenPropertyPermissions(alice, [{
+ key: `${maxPropertiesPerItem}-th`,
+ permission: {mutable: true, tokenOwner: true, collectionAdmin: true},
+ }])).to.be.rejectedWith(/common\.PropertyLimitReached/);
+ }));
});
describe('ReFungible token properties permissions tests', () => {
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -1100,6 +1100,13 @@
return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();
}
+ async getPropertiesConsumedSpace(collectionId: number): Promise<number> {
+ const api = this.helper.getApi();
+ const props = (await api.query.common.collectionProperties(collectionId)).toJSON();
+
+ return (props! as any).consumedSpace;
+ }
+
async getCollectionOptions(collectionId: number) {
return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();
}
@@ -3035,6 +3042,10 @@
return await this.helper.collection.getProperties(this.collectionId, propertyKeys);
}
+ async getPropertiesConsumedSpace() {
+ return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);
+ }
+
async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {
return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);
}
@@ -3158,6 +3169,13 @@
return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);
}
+ async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {
+ const api = this.helper.getApi();
+ const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();
+
+ return (props! as any).consumedSpace;
+ }
+
async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {
return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);
}
@@ -3269,6 +3287,13 @@
return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);
}
+ async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {
+ const api = this.helper.getApi();
+ const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();
+
+ return (props! as any).consumedSpace;
+ }
+
async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {
return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);
}
@@ -3421,6 +3446,10 @@
return await this.collection.getTokenProperties(this.tokenId, propertyKeys);
}
+ async getTokenPropertiesConsumedSpace() {
+ return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);
+ }
+
async setProperties(signer: TSigner, properties: IProperty[]) {
return await this.collection.setTokenProperties(signer, this.tokenId, properties);
}