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.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
@@ -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.tsdiffbeforeafterboth1// 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/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {itSub, Pallets, usingPlaygrounds, expect} from '../util';19import {UniqueBaseCollection} from '../util/playgrounds/unique';2021describe('Integration Test: Collection Properties', () => {22 let alice: IKeyringPair;23 let bob: IKeyringPair;24 25 before(async () => {26 await usingPlaygrounds(async (helper, privateKey) => {27 const donor = await privateKey({filename: __filename});28 [alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);29 });30 });31 32 itSub('Properties are initially empty', async ({helper}) => {33 const collection = await helper.nft.mintCollection(alice);34 expect(await collection.getProperties()).to.be.empty;35 });36 37 async function testSetsPropertiesForCollection(collection: UniqueBaseCollection) {38 // As owner39 await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}])).to.be.fulfilled;40 41 await collection.addAdmin(alice, {Substrate: bob.address});42 43 // As administrator44 await expect(collection.setProperties(bob, [{key: 'black_hole'}])).to.be.fulfilled;45 46 const properties = await collection.getProperties();47 expect(properties).to.include.deep.members([48 {key: 'electron', value: 'come bond'},49 {key: 'black_hole', value: ''},50 ]);51 }52 53 itSub('Sets properties for a NFT collection', async ({helper}) => {54 await testSetsPropertiesForCollection(await helper.nft.mintCollection(alice));55 });56 57 itSub.ifWithPallets('Sets properties for a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {58 await testSetsPropertiesForCollection(await helper.rft.mintCollection(alice));59 });60 61 async function testCheckValidNames(collection: UniqueBaseCollection) {62 // alpha symbols63 await expect(collection.setProperties(alice, [{key: 'answer'}])).to.be.fulfilled;64 65 // numeric symbols66 await expect(collection.setProperties(alice, [{key: '451'}])).to.be.fulfilled;67 68 // underscore symbol69 await expect(collection.setProperties(alice, [{key: 'black_hole'}])).to.be.fulfilled;70 71 // dash symbol72 await expect(collection.setProperties(alice, [{key: '-'}])).to.be.fulfilled;73 74 // dot symbol75 await expect(collection.setProperties(alice, [{key: 'once.in.a.long.long.while...', value: 'you get a little lost'}])).to.be.fulfilled;76 77 const properties = await collection.getProperties();78 expect(properties).to.include.deep.members([79 {key: 'answer', value: ''},80 {key: '451', value: ''},81 {key: 'black_hole', value: ''},82 {key: '-', value: ''},83 {key: 'once.in.a.long.long.while...', value: 'you get a little lost'},84 ]);85 }86 87 itSub('Check valid names for NFT collection properties keys', async ({helper}) => {88 await testCheckValidNames(await helper.nft.mintCollection(alice));89 });90 91 itSub.ifWithPallets('Check valid names for ReFungible collection properties keys', [Pallets.ReFungible], async ({helper}) => {92 await testCheckValidNames(await helper.rft.mintCollection(alice));93 });94 95 async function testChangesProperties(collection: UniqueBaseCollection) {96 await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: ''}])).to.be.fulfilled;97 98 // Mutate the properties99 await expect(collection.setProperties(alice, [{key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;100 101 const properties = await collection.getProperties();102 expect(properties).to.include.deep.members([103 {key: 'electron', value: 'come bond'},104 {key: 'black_hole', value: 'LIGO'},105 ]);106 }107 108 itSub('Changes properties of a NFT collection', async ({helper}) => {109 await testChangesProperties(await helper.nft.mintCollection(alice));110 });111 112 itSub.ifWithPallets('Changes properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {113 await testChangesProperties(await helper.rft.mintCollection(alice));114 });115 116 async function testDeleteProperties(collection: UniqueBaseCollection) {117 await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;118 119 await expect(collection.deleteProperties(alice, ['electron'])).to.be.fulfilled;120 121 const properties = await collection.getProperties(['black_hole', 'electron']);122 expect(properties).to.be.deep.equal([123 {key: 'black_hole', value: 'LIGO'},124 ]);125 }126 127 itSub('Deletes properties of a NFT collection', async ({helper}) => {128 await testDeleteProperties(await helper.nft.mintCollection(alice));129 });130 131 itSub.ifWithPallets('Deletes properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {132 await testDeleteProperties(await helper.rft.mintCollection(alice));133 });134});135 136describe('Negative Integration Test: Collection Properties', () => {137 let alice: IKeyringPair;138 let bob: IKeyringPair;139 140 before(async () => {141 await usingPlaygrounds(async (helper, privateKey) => {142 const donor = await privateKey({filename: __filename});143 [alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);144 });145 });146 147 async function testFailsSetPropertiesIfNotOwnerOrAdmin(collection: UniqueBaseCollection) { 148 await expect(collection.setProperties(bob, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]))149 .to.be.rejectedWith(/common\.NoPermission/);150 151 expect(await collection.getProperties()).to.be.empty;152 }153 154 itSub('Fails to set properties in a NFT collection if not its onwer/administrator', async ({helper}) => {155 await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.nft.mintCollection(alice));156 });157 158 itSub.ifWithPallets('Fails to set properties in a ReFungible collection if not its onwer/administrator', [Pallets.ReFungible], async ({helper}) => {159 await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.rft.mintCollection(alice));160 });161 162 async function testFailsSetPropertiesThatExeedLimits(collection: UniqueBaseCollection) {163 const spaceLimit = (await (collection.helper!.api! as any).query.common.collectionProperties(collection.collectionId)).spaceLimit.toNumber();164 165 // Mute the general tx parsing error, too many bytes to process166 {167 console.error = () => {};168 await expect(collection.setProperties(alice, [169 {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 9))},170 ])).to.be.rejected;171 }172 173 expect(await collection.getProperties(['electron'])).to.be.empty;174 175 await expect(collection.setProperties(alice, [176 {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 18))}, 177 {key: 'black_hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))}, 178 ])).to.be.rejectedWith(/common\.NoSpaceForProperty/);179 180 expect(await collection.getProperties(['electron', 'black_hole'])).to.be.empty;181 }182 183 itSub('Fails to set properties that exceed the limits (NFT)', async ({helper}) => {184 await testFailsSetPropertiesThatExeedLimits(await helper.nft.mintCollection(alice));185 });186 187 itSub.ifWithPallets('Fails to set properties that exceed the limits (ReFungible)', [Pallets.ReFungible], async ({helper}) => {188 await testFailsSetPropertiesThatExeedLimits(await helper.rft.mintCollection(alice));189 });190 191 async function testFailsSetMorePropertiesThanAllowed(collection: UniqueBaseCollection) {192 const propertiesToBeSet = [];193 for (let i = 0; i < 65; i++) {194 propertiesToBeSet.push({195 key: 'electron_' + i,196 value: Math.random() > 0.5 ? 'high' : 'low',197 });198 }199 200 await expect(collection.setProperties(alice, propertiesToBeSet)).201 to.be.rejectedWith(/common\.PropertyLimitReached/);202 203 expect(await collection.getProperties()).to.be.empty;204 }205 206 itSub('Fails to set more properties than it is allowed (NFT)', async ({helper}) => {207 await testFailsSetMorePropertiesThanAllowed(await helper.nft.mintCollection(alice));208 });209 210 itSub.ifWithPallets('Fails to set more properties than it is allowed (ReFungible)', [Pallets.ReFungible], async ({helper}) => {211 await testFailsSetMorePropertiesThanAllowed(await helper.rft.mintCollection(alice));212 });213 214 async function testFailsSetPropertiesWithInvalidNames(collection: UniqueBaseCollection) {215 const invalidProperties = [216 [{key: 'electron', value: 'negative'}, {key: 'string theory', value: 'understandable'}],217 [{key: 'Mr/Sandman', value: 'Bring me a gene'}],218 [{key: 'déjà vu', value: 'hmm...'}],219 ];220 221 for (let i = 0; i < invalidProperties.length; i++) {222 await expect(223 collection.setProperties(alice, invalidProperties[i]), 224 `on rejecting the new badly-named property #${i}`,225 ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);226 }227 228 await expect(229 collection.setProperties(alice, [{key: '', value: 'nothing must not exist'}]), 230 'on rejecting an unnamed property',231 ).to.be.rejectedWith(/common\.EmptyPropertyKey/);232 233 await expect(234 collection.setProperties(alice, [{key: 'CRISPR-Cas9', value: 'rewriting nature!'}]), 235 'on setting the correctly-but-still-badly-named property',236 ).to.be.fulfilled;237 238 const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat('CRISPR-Cas9').concat('');239 240 const properties = await collection.getProperties(keys);241 expect(properties).to.be.deep.equal([242 {key: 'CRISPR-Cas9', value: 'rewriting nature!'},243 ]);244 245 for (let i = 0; i < invalidProperties.length; i++) {246 await expect(247 collection.deleteProperties(alice, invalidProperties[i].map(propertySet => propertySet.key)), 248 `on trying to delete the non-existent badly-named property #${i}`,249 ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);250 }251 }252 253 itSub('Fails to set properties with invalid names (NFT)', async ({helper}) => {254 await testFailsSetPropertiesWithInvalidNames(await helper.nft.mintCollection(alice));255 });256 257 itSub.ifWithPallets('Fails to set properties with invalid names (ReFungible)', [Pallets.ReFungible], async ({helper}) => {258 await testFailsSetPropertiesWithInvalidNames(await helper.rft.mintCollection(alice));259 });260});261 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/>.1617import {IKeyringPair} from '@polkadot/types/types';18import {itSub, Pallets, usingPlaygrounds, expect} from '../util';19import {UniqueBaseCollection} from '../util/playgrounds/unique';2021describe('Integration Test: Collection Properties', () => {22 let alice: IKeyringPair;23 let bob: IKeyringPair;24 25 before(async () => {26 await usingPlaygrounds(async (helper, privateKey) => {27 const donor = await privateKey({filename: __filename});28 [alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);29 });30 });31 32 itSub('Properties are initially empty', async ({helper}) => {33 const collection = await helper.nft.mintCollection(alice);34 expect(await collection.getProperties()).to.be.empty;35 });36 37 async function testSetsPropertiesForCollection(collection: UniqueBaseCollection) {38 // As owner39 await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}])).to.be.fulfilled;40 41 await collection.addAdmin(alice, {Substrate: bob.address});42 43 // As administrator44 await expect(collection.setProperties(bob, [{key: 'black_hole'}])).to.be.fulfilled;45 46 const properties = await collection.getProperties();47 expect(properties).to.include.deep.members([48 {key: 'electron', value: 'come bond'},49 {key: 'black_hole', value: ''},50 ]);51 }52 53 itSub('Sets properties for a NFT collection', async ({helper}) => {54 await testSetsPropertiesForCollection(await helper.nft.mintCollection(alice));55 });56 57 itSub.ifWithPallets('Sets properties for a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {58 await testSetsPropertiesForCollection(await helper.rft.mintCollection(alice));59 });60 61 async function testCheckValidNames(collection: UniqueBaseCollection) {62 // alpha symbols63 await expect(collection.setProperties(alice, [{key: 'answer'}])).to.be.fulfilled;64 65 // numeric symbols66 await expect(collection.setProperties(alice, [{key: '451'}])).to.be.fulfilled;67 68 // underscore symbol69 await expect(collection.setProperties(alice, [{key: 'black_hole'}])).to.be.fulfilled;70 71 // dash symbol72 await expect(collection.setProperties(alice, [{key: '-'}])).to.be.fulfilled;73 74 // dot symbol75 await expect(collection.setProperties(alice, [{key: 'once.in.a.long.long.while...', value: 'you get a little lost'}])).to.be.fulfilled;76 77 const properties = await collection.getProperties();78 expect(properties).to.include.deep.members([79 {key: 'answer', value: ''},80 {key: '451', value: ''},81 {key: 'black_hole', value: ''},82 {key: '-', value: ''},83 {key: 'once.in.a.long.long.while...', value: 'you get a little lost'},84 ]);85 }86 87 itSub('Check valid names for NFT collection properties keys', async ({helper}) => {88 await testCheckValidNames(await helper.nft.mintCollection(alice));89 });90 91 itSub.ifWithPallets('Check valid names for ReFungible collection properties keys', [Pallets.ReFungible], async ({helper}) => {92 await testCheckValidNames(await helper.rft.mintCollection(alice));93 });94 95 async function testChangesProperties(collection: UniqueBaseCollection) {96 await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: ''}])).to.be.fulfilled;97 98 // Mutate the properties99 await expect(collection.setProperties(alice, [{key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;100 101 const properties = await collection.getProperties();102 expect(properties).to.include.deep.members([103 {key: 'electron', value: 'come bond'},104 {key: 'black_hole', value: 'LIGO'},105 ]);106 }107 108 itSub('Changes properties of a NFT collection', async ({helper}) => {109 await testChangesProperties(await helper.nft.mintCollection(alice));110 });111 112 itSub.ifWithPallets('Changes properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {113 await testChangesProperties(await helper.rft.mintCollection(alice));114 });115 116 async function testDeleteProperties(collection: UniqueBaseCollection) {117 await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;118 119 await expect(collection.deleteProperties(alice, ['electron'])).to.be.fulfilled;120 121 const properties = await collection.getProperties(['black_hole', 'electron']);122 expect(properties).to.be.deep.equal([123 {key: 'black_hole', value: 'LIGO'},124 ]);125 }126 127 itSub('Deletes properties of a NFT collection', async ({helper}) => {128 await testDeleteProperties(await helper.nft.mintCollection(alice));129 });130 131 itSub.ifWithPallets('Deletes properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {132 await testDeleteProperties(await helper.rft.mintCollection(alice));133 });134135 [136 // TODO enable properties for FT collection in Substrate (release 040)137 // {mode: 'ft' as const, requiredPallets: []},138 {mode: 'nft' as const, requiredPallets: []},139 {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]}, 140 ].map(testCase =>141 itSub.ifWithPallets(`Allows modifying a collection property multiple times (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {142 const propKey = 'tok-prop';143144 const collection = await helper[testCase.mode].mintCollection(alice);145146 const maxCollectionPropertiesSize = 40960;147148 const propDataSize = 4096;149150 let propDataChar = 'a';151 const makeNewPropData = () => {152 propDataChar = String.fromCharCode(propDataChar.charCodeAt(0) + 1);153 return `${propDataChar}`.repeat(propDataSize);154 };155156 await collection.setProperties(alice, [{key: propKey, value: makeNewPropData()}]);157 const originalSpace = await collection.getPropertiesConsumedSpace();158 expect(originalSpace).to.be.equal(propDataSize);159160 const sameSizePropertiesPossibleNum = maxCollectionPropertiesSize / propDataSize;161162 // It is possible to modify a property as many times as needed.163 // It will not consume any additional space.164 for (let i = 0; i < sameSizePropertiesPossibleNum + 1; i++) {165 await collection.setProperties(alice, [{key: propKey, value: makeNewPropData()}]);166 const consumedSpace = await collection.getPropertiesConsumedSpace();167 expect(consumedSpace).to.be.equal(originalSpace);168 }169 }));170171 [172 // TODO enable properties for FT collection in Substrate (release 040)173 // {mode: 'ft' as const, requiredPallets: []},174 {mode: 'nft' as const, requiredPallets: []},175 {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]}, 176 ].map(testCase =>177 itSub.ifWithPallets(`Adding then removing a collection property doesn't change the consumed space (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {178 const propKey = 'tok-prop';179180 const collection = await helper[testCase.mode].mintCollection(alice);181 const originalSpace = await collection.getPropertiesConsumedSpace();182183 const propDataSize = 4096;184 const propData = 'a'.repeat(propDataSize);185186 await collection.setProperties(alice, [{key: propKey, value: propData}]);187 let consumedSpace = await collection.getPropertiesConsumedSpace();188 expect(consumedSpace).to.be.equal(propDataSize);189190 await collection.deleteProperties(alice, [propKey]);191 consumedSpace = await collection.getPropertiesConsumedSpace();192 expect(consumedSpace).to.be.equal(originalSpace);193 }));194});195 196describe('Negative Integration Test: Collection Properties', () => {197 let alice: IKeyringPair;198 let bob: IKeyringPair;199 200 before(async () => {201 await usingPlaygrounds(async (helper, privateKey) => {202 const donor = await privateKey({filename: __filename});203 [alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);204 });205 });206 207 async function testFailsSetPropertiesIfNotOwnerOrAdmin(collection: UniqueBaseCollection) { 208 await expect(collection.setProperties(bob, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]))209 .to.be.rejectedWith(/common\.NoPermission/);210 211 expect(await collection.getProperties()).to.be.empty;212 }213 214 itSub('Fails to set properties in a NFT collection if not its onwer/administrator', async ({helper}) => {215 await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.nft.mintCollection(alice));216 });217 218 itSub.ifWithPallets('Fails to set properties in a ReFungible collection if not its onwer/administrator', [Pallets.ReFungible], async ({helper}) => {219 await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.rft.mintCollection(alice));220 });221 222 async function testFailsSetPropertiesThatExeedLimits(collection: UniqueBaseCollection) {223 const spaceLimit = (await (collection.helper!.api! as any).query.common.collectionProperties(collection.collectionId)).spaceLimit.toNumber();224 225 // Mute the general tx parsing error, too many bytes to process226 {227 console.error = () => {};228 await expect(collection.setProperties(alice, [229 {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 9))},230 ])).to.be.rejected;231 }232 233 expect(await collection.getProperties(['electron'])).to.be.empty;234 235 await expect(collection.setProperties(alice, [236 {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 18))}, 237 {key: 'black_hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))}, 238 ])).to.be.rejectedWith(/common\.NoSpaceForProperty/);239 240 expect(await collection.getProperties(['electron', 'black_hole'])).to.be.empty;241 }242 243 itSub('Fails to set properties that exceed the limits (NFT)', async ({helper}) => {244 await testFailsSetPropertiesThatExeedLimits(await helper.nft.mintCollection(alice));245 });246 247 itSub.ifWithPallets('Fails to set properties that exceed the limits (ReFungible)', [Pallets.ReFungible], async ({helper}) => {248 await testFailsSetPropertiesThatExeedLimits(await helper.rft.mintCollection(alice));249 });250 251 async function testFailsSetMorePropertiesThanAllowed(collection: UniqueBaseCollection) {252 const propertiesToBeSet = [];253 for (let i = 0; i < 65; i++) {254 propertiesToBeSet.push({255 key: 'electron_' + i,256 value: Math.random() > 0.5 ? 'high' : 'low',257 });258 }259 260 await expect(collection.setProperties(alice, propertiesToBeSet)).261 to.be.rejectedWith(/common\.PropertyLimitReached/);262 263 expect(await collection.getProperties()).to.be.empty;264 }265 266 itSub('Fails to set more properties than it is allowed (NFT)', async ({helper}) => {267 await testFailsSetMorePropertiesThanAllowed(await helper.nft.mintCollection(alice));268 });269 270 itSub.ifWithPallets('Fails to set more properties than it is allowed (ReFungible)', [Pallets.ReFungible], async ({helper}) => {271 await testFailsSetMorePropertiesThanAllowed(await helper.rft.mintCollection(alice));272 });273 274 async function testFailsSetPropertiesWithInvalidNames(collection: UniqueBaseCollection) {275 const invalidProperties = [276 [{key: 'electron', value: 'negative'}, {key: 'string theory', value: 'understandable'}],277 [{key: 'Mr/Sandman', value: 'Bring me a gene'}],278 [{key: 'déjà vu', value: 'hmm...'}],279 ];280 281 for (let i = 0; i < invalidProperties.length; i++) {282 await expect(283 collection.setProperties(alice, invalidProperties[i]), 284 `on rejecting the new badly-named property #${i}`,285 ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);286 }287 288 await expect(289 collection.setProperties(alice, [{key: '', value: 'nothing must not exist'}]), 290 'on rejecting an unnamed property',291 ).to.be.rejectedWith(/common\.EmptyPropertyKey/);292 293 await expect(294 collection.setProperties(alice, [{key: 'CRISPR-Cas9', value: 'rewriting nature!'}]), 295 'on setting the correctly-but-still-badly-named property',296 ).to.be.fulfilled;297 298 const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat('CRISPR-Cas9').concat('');299 300 const properties = await collection.getProperties(keys);301 expect(properties).to.be.deep.equal([302 {key: 'CRISPR-Cas9', value: 'rewriting nature!'},303 ]);304 305 for (let i = 0; i < invalidProperties.length; i++) {306 await expect(307 collection.deleteProperties(alice, invalidProperties[i].map(propertySet => propertySet.key)), 308 `on trying to delete the non-existent badly-named property #${i}`,309 ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);310 }311 }312 313 itSub('Fails to set properties with invalid names (NFT)', async ({helper}) => {314 await testFailsSetPropertiesWithInvalidNames(await helper.nft.mintCollection(alice));315 });316 317 itSub.ifWithPallets('Fails to set properties with invalid names (ReFungible)', [Pallets.ReFungible], async ({helper}) => {318 await testFailsSetPropertiesWithInvalidNames(await helper.rft.mintCollection(alice));319 });320});321 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);
}