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.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.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 super::*;18use crate::{Pallet, Config, NonfungibleHandle};1920use frame_benchmarking::{benchmarks, account};21use pallet_common::{22 bench_init,23 benchmarking::{create_collection_raw, property_key, property_value},24 CommonCollectionOperations,25};26use sp_std::prelude::*;27use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, budget::Unlimited};2829const SEED: u32 = 1;3031fn create_max_item_data<T: Config>(owner: T::CrossAccountId) -> CreateItemData<T> {32 CreateItemData::<T> {33 owner,34 properties: Default::default(),35 }36}37fn create_max_item<T: Config>(38 collection: &NonfungibleHandle<T>,39 sender: &T::CrossAccountId,40 owner: T::CrossAccountId,41) -> Result<TokenId, DispatchError> {42 <Pallet<T>>::create_item(43 &collection,44 sender,45 create_max_item_data::<T>(owner),46 &Unlimited,47 )?;48 Ok(TokenId(<TokensMinted<T>>::get(&collection.id)))49}5051fn create_collection<T: Config>(52 owner: T::CrossAccountId,53) -> Result<NonfungibleHandle<T>, DispatchError> {54 create_collection_raw(55 owner,56 CollectionMode::NFT,57 |owner: T::CrossAccountId, data| {58 <Pallet<T>>::init_collection(owner.clone(), owner, data, Default::default())59 },60 NonfungibleHandle::cast,61 )62}6364benchmarks! {65 create_item {66 bench_init!{67 owner: sub; collection: collection(owner);68 sender: cross_from_sub(owner); to: cross_sub;69 };70 }: {create_max_item(&collection, &sender, to.clone())?}7172 create_multiple_items {73 let b in 0..MAX_ITEMS_PER_BATCH;74 bench_init!{75 owner: sub; collection: collection(owner);76 sender: cross_from_sub(owner); to: cross_sub;77 };78 let data = (0..b).map(|_| create_max_item_data::<T>(to.clone())).collect();79 }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data, &Unlimited)?}8081 create_multiple_items_ex {82 let b in 0..MAX_ITEMS_PER_BATCH;83 bench_init!{84 owner: sub; collection: collection(owner);85 sender: cross_from_sub(owner);86 };87 let data = (0..b).map(|i| {88 bench_init!(to: cross_sub(i););89 create_max_item_data::<T>(to)90 }).collect();91 }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data, &Unlimited)?}9293 burn_item {94 bench_init!{95 owner: sub; collection: collection(owner);96 sender: cross_from_sub(owner); burner: cross_sub;97 };98 let item = create_max_item(&collection, &sender, burner.clone())?;99 }: {<Pallet<T>>::burn(&collection, &burner, item)?}100101 burn_recursively_self_raw {102 bench_init!{103 owner: sub; collection: collection(owner);104 sender: cross_from_sub(owner); burner: cross_sub;105 };106 let item = create_max_item(&collection, &sender, burner.clone())?;107 }: {<Pallet<T>>::burn_recursively(&collection, &burner, item, &Unlimited, &Unlimited)?}108109 burn_recursively_breadth_plus_self_plus_self_per_each_raw {110 let b in 0..200;111 bench_init!{112 owner: sub; collection: collection(owner);113 sender: cross_from_sub(owner); burner: cross_sub;114 };115 let item = create_max_item(&collection, &sender, burner.clone())?;116 for i in 0..b {117 create_max_item(&collection, &sender, T::CrossTokenAddressMapping::token_to_address(collection.id, item))?;118 }119 }: {<Pallet<T>>::burn_recursively(&collection, &burner, item, &Unlimited, &Unlimited)?}120121 transfer {122 bench_init!{123 owner: sub; collection: collection(owner);124 owner: cross_from_sub; sender: cross_sub; receiver: cross_sub;125 };126 let item = create_max_item(&collection, &owner, sender.clone())?;127 }: {<Pallet<T>>::transfer(&collection, &sender, &receiver, item, &Unlimited)?}128129 approve {130 bench_init!{131 owner: sub; collection: collection(owner);132 owner: cross_from_sub; sender: cross_sub; spender: cross_sub;133 };134 let item = create_max_item(&collection, &owner, sender.clone())?;135 }: {<Pallet<T>>::set_allowance(&collection, &sender, item, Some(&spender))?}136137 transfer_from {138 bench_init!{139 owner: sub; collection: collection(owner);140 owner: cross_from_sub; sender: cross_sub; spender: cross_sub; receiver: cross_sub;141 };142 let item = create_max_item(&collection, &owner, sender.clone())?;143 <Pallet<T>>::set_allowance(&collection, &sender, item, Some(&spender))?;144 }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, &Unlimited)?}145146 burn_from {147 bench_init!{148 owner: sub; collection: collection(owner);149 owner: cross_from_sub; sender: cross_sub; burner: cross_sub;150 };151 let item = create_max_item(&collection, &owner, sender.clone())?;152 <Pallet<T>>::set_allowance(&collection, &sender, item, Some(&burner))?;153 }: {<Pallet<T>>::burn_from(&collection, &burner, &sender, item, &Unlimited)?}154155 set_token_property_permissions {156 let b in 0..MAX_PROPERTIES_PER_ITEM;157 bench_init!{158 owner: sub; collection: collection(owner);159 owner: cross_from_sub;160 };161 let perms = (0..b).map(|k| PropertyKeyPermission {162 key: property_key(k as usize),163 permission: PropertyPermission {164 mutable: false,165 collection_admin: false,166 token_owner: false,167 },168 }).collect::<Vec<_>>();169 }: {<Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?}170171 set_token_properties {172 let b in 0..MAX_PROPERTIES_PER_ITEM;173 bench_init!{174 owner: sub; collection: collection(owner);175 owner: cross_from_sub;176 };177 let perms = (0..b).map(|k| PropertyKeyPermission {178 key: property_key(k as usize),179 permission: PropertyPermission {180 mutable: false,181 collection_admin: true,182 token_owner: true,183 },184 }).collect::<Vec<_>>();185 <Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;186 let props = (0..b).map(|k| Property {187 key: property_key(k as usize),188 value: property_value(),189 }).collect::<Vec<_>>();190 let item = create_max_item(&collection, &owner, owner.clone())?;191 }: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), false, &Unlimited)?}192193 delete_token_properties {194 let b in 0..MAX_PROPERTIES_PER_ITEM;195 bench_init!{196 owner: sub; collection: collection(owner);197 owner: cross_from_sub;198 };199 let perms = (0..b).map(|k| PropertyKeyPermission {200 key: property_key(k as usize),201 permission: PropertyPermission {202 mutable: true,203 collection_admin: true,204 token_owner: true,205 },206 }).collect::<Vec<_>>();207 <Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;208 let props = (0..b).map(|k| Property {209 key: property_key(k as usize),210 value: property_value(),211 }).collect::<Vec<_>>();212 let item = create_max_item(&collection, &owner, owner.clone())?;213 <Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), false, &Unlimited)?;214 let to_delete = (0..b).map(|k| property_key(k as usize)).collect::<Vec<_>>();215 }: {<Pallet<T>>::delete_token_properties(&collection, &owner, item, to_delete.into_iter(), &Unlimited)?}216217 token_owner {218 bench_init!{219 owner: sub; collection: collection(owner);220 owner: cross_from_sub;221 };222 let item = create_max_item(&collection, &owner, owner.clone())?;223224 }: {collection.token_owner(item)}225226 set_allowance_for_all {227 bench_init!{228 owner: sub; collection: collection(owner); owner: cross_from_sub;229 operator: cross_sub;230 };231 }: {<Pallet<T>>::set_allowance_for_all(&collection, &owner, &operator, true)}232233 allowance_for_all {234 bench_init!{235 owner: sub; collection: collection(owner); owner: cross_from_sub;236 operator: cross_sub;237 };238 }: {<Pallet<T>>::allowance_for_all(&collection, &owner, &operator)}239}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', () => {