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.jsondiffbeforeafterboth1{2 "name": "unique-tests",3 "version": "1.0.0",4 "description": "Unique Chain Tests",5 "main": "",6 "devDependencies": {7 "@polkadot/typegen": "9.9.4",8 "@types/chai": "^4.3.3",9 "@types/chai-as-promised": "^7.1.5",10 "@types/chai-like": "^1.1.1",11 "@types/mocha": "^10.0.0",12 "@types/node": "^18.11.2",13 "@typescript-eslint/eslint-plugin": "^5.40.1",14 "@typescript-eslint/parser": "^5.40.1",15 "chai": "^4.3.6",16 "eslint": "^8.25.0",17 "eslint-plugin-mocha": "^10.1.0",18 "mocha": "^10.1.0",19 "ts-node": "^10.9.1",20 "typescript": "^4.8.4"21 },22 "mocha": {23 "timeout": 9999999,24 "require": [25 "ts-node/register"26 ]27 },28 "scripts": {29 "lint": "eslint --ext .ts,.js src/",30 "fix": "eslint --ext .ts,.js src/ --fix",31 "setup": "ts-node ./src/util/globalSetup.ts",32 "test": "yarn setup && mocha --timeout 9999999 -r ts-node/register './src/**/*.*test.ts'",33 "testParallelFull": "yarn testParallel && yarn testSequential",34 "testParallel": "yarn setup && mocha --parallel --timeout 9999999 -r ts-node/register './src/**/*.test.ts'",35 "testSequential": "yarn setup && mocha --timeout 9999999 -r ts-node/register './src/**/*.seqtest.ts'",36 "testStructure": "yarn setup && mocha --timeout 9999999 -r ts-node/register ./**/nesting/*.*test.ts",37 "testEth": "yarn setup && mocha --timeout 9999999 -r ts-node/register './**/eth/**/*.*test.ts'",38 "testEthNesting": "yarn setup && mocha --timeout 9999999 -r ts-node/register './**/eth/nesting/**/*.*test.ts'",39 "testEthFractionalizer": "yarn setup && mocha --timeout 9999999 -r ts-node/register './**/eth/fractionalizer/**/*.*test.ts'",40 "testEthMarketplace": "yarn setup && mocha --timeout 9999999 -r ts-node/register './**/eth/marketplace/**/*.*test.ts'",41 "testEvent": "yarn setup && mocha --timeout 9999999 -r ts-node/register ./src/check-event/*.*test.ts",42 "testRmrk": "yarn setup && mocha --timeout 9999999 -r ts-node/register ./**/rmrk/*.*test.ts",43 "testEthPayable": "mocha --timeout 9999999 -r ts-node/register './**/eth/payable.test.ts'",44 "testEthTokenProperties": "mocha --timeout 9999999 -r ts-node/register ./**/eth/tokenProperties.test.ts",45 "testEvmCoder": "mocha --timeout 9999999 -r ts-node/register './**/eth/evmCoder.test.ts'",46 "testNesting": "mocha --timeout 9999999 -r ts-node/register ./**/nest.test.ts",47 "testUnnesting": "mocha --timeout 9999999 -r ts-node/register ./**/unnest.test.ts",48 "testProperties": "mocha --timeout 9999999 -r ts-node/register ./**/properties.test.ts ./**/getPropertiesRpc.test.ts",49 "testMigration": "mocha --timeout 9999999 -r ts-node/register ./**/nesting/migration-check.test.ts",50 "testAddCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/addCollectionAdmin.test.ts",51 "testSetCollectionLimits": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionLimits.test.ts",52 "testChangeCollectionOwner": "mocha --timeout 9999999 -r ts-node/register ./**/change-collection-owner.test.ts",53 "testSetCollectionSponsor": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionSponsor.test.ts",54 "testConfirmSponsorship": "mocha --timeout 9999999 --parallel -r ts-node/register ./**/confirmSponsorship.test.ts",55 "testRemoveCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionAdmin.test.ts",56 "testRemoveCollectionSponsor": "mocha --timeout 9999999 -r ts-node/register ./**/removeCollectionSponsor.test.ts",57 "testAllowLists": "mocha --timeout 9999999 -r ts-node/register ./**/allowLists.test.ts",58 "testConnection": "mocha --timeout 9999999 -r ts-node/register ./**/connection.test.ts",59 "testContracts": "mocha --timeout 9999999 -r ts-node/register ./**/contracts.test.ts",60 "testCreateItem": "mocha --timeout 9999999 -r ts-node/register ./**/createItem.test.ts",61 "testCreateMultipleItems": "mocha --timeout 9999999 -r ts-node/register ./**/createMultipleItems.test.ts",62 "testCreateMultipleItemsEx": "mocha --timeout 9999999 -r ts-node/register ./**/createMultipleItemsEx.test.ts",63 "testApprove": "mocha --timeout 9999999 -r ts-node/register ./**/approve.test.ts",64 "testTransferFrom": "mocha --timeout 9999999 -r ts-node/register ./**/transferFrom.test.ts",65 "testCreateCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts",66 "testDestroyCollection": "mocha --timeout 9999999 -r ts-node/register ./**/destroyCollection.test.ts",67 "testToggleContractAllowList": "mocha --timeout 9999999 -r ts-node/register ./**/toggleContractAllowList.test.ts",68 "testAddToContractAllowList": "mocha --timeout 9999999 -r ts-node/register ./**/addToContractAllowList.test.ts",69 "testTransfer": "mocha --timeout 9999999 -r ts-node/register ./**/transfer.test.ts",70 "testBurnItem": "mocha --timeout 9999999 -r ts-node/register ./**/burnItem.test.ts",71 "testAdminTransferAndBurn": "mocha --timeout 9999999 -r ts-node/register ./**/adminTransferAndBurn.test.ts",72 "testSetPermissions": "mocha --timeout 9999999 -r ts-node/register ./**/setPermissions.test.ts",73 "testCreditFeesToTreasury": "mocha --timeout 9999999 -r ts-node/register ./**/creditFeesToTreasury.seqtest.ts",74 "testContractSponsoring": "mocha --timeout 9999999 -r ts-node/register ./**/eth/contractSponsoring.test.ts",75 "testEnableContractSponsoring": "mocha --timeout 9999999 -r ts-node/register ./**/enableContractSponsoring.test.ts",76 "testRemoveFromContractAllowList": "mocha --timeout 9999999 -r ts-node/register ./**/removeFromContractAllowList.test.ts",77 "testSetContractSponsoringRateLimit": "mocha --timeout 9999999 -r ts-node/register ./**/setContractSponsoringRateLimit.test.ts",78 "testSetOffchainSchema": "mocha --timeout 9999999 -r ts-node/register ./**/setOffchainSchema.test.ts",79 "testNextSponsoring": "mocha --timeout 9999999 -r ts-node/register ./**/nextSponsoring.test.ts",80 "testOverflow": "mocha --timeout 9999999 -r ts-node/register ./**/overflow.test.ts",81 "testMaintenance": "mocha --timeout 9999999 -r ts-node/register ./**/maintenanceMode.seqtest.ts",82 "testInflation": "mocha --timeout 9999999 -r ts-node/register ./**/inflation.seqtest.ts",83 "testScheduler": "mocha --timeout 9999999 -r ts-node/register ./**/scheduler.seqtest.ts",84 "testSchedulingEVM": "mocha --timeout 9999999 -r ts-node/register ./**/eth/scheduling.test.ts",85 "testPalletPresence": "mocha --timeout 9999999 -r ts-node/register ./**/pallet-presence.test.ts",86 "testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts",87 "testEnableDisableTransfers": "mocha --timeout 9999999 -r ts-node/register ./**/enableDisableTransfer.test.ts",88 "testLimits": "mocha --timeout 9999999 -r ts-node/register ./**/limits.test.ts",89 "testEthCreateNFTCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createNFTCollection.test.ts",90 "testEthCreateRFTCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createRFTCollection.test.ts",91 "testEthNFT": "mocha --timeout 9999999 -r ts-node/register ./**/eth/nonFungible.test.ts",92 "testRFT": "mocha --timeout 9999999 -r ts-node/register ./**/refungible.test.ts",93 "testEthRFT": "mocha --timeout 9999999 -r ts-node/register ./**/eth/reFungible.test.ts ./**/eth/reFungibleToken.test.ts",94 "testFT": "mocha --timeout 9999999 -r ts-node/register ./**/fungible.test.ts",95 "testEthFT": "mocha --timeout 9999999 -r ts-node/register ./**/eth/fungible.test.ts",96 "testRPC": "mocha --timeout 9999999 -r ts-node/register ./**/rpc.test.ts",97 "testPromotion": "yarn setup && mocha --timeout 9999999 -r ts-node/register ./**/app-promotion.*test.ts",98 "testXcmUnique": "RUN_XCM_TESTS=1 mocha --timeout 9999999 -r ts-node/register ./**/xcm/xcmUnique.test.ts",99 "testXcmQuartz": "RUN_XCM_TESTS=1 mocha --timeout 9999999 -r ts-node/register ./**/xcm/xcmQuartz.test.ts",100 "testXcmOpal": "RUN_XCM_TESTS=1 mocha --timeout 9999999 -r ts-node/register ./**/xcm/xcmOpal.test.ts",101 "testXcmTransferAcala": "mocha --timeout 9999999 -r ts-node/register ./**/xcm/xcmTransferAcala.test.ts acalaId=2000 uniqueId=5000",102 "testXcmTransferStatemine": "mocha --timeout 9999999 -r ts-node/register ./**/xcm/xcmTransferStatemine.test.ts statemineId=1000 uniqueId=5000",103 "testXcmTransferMoonbeam": "mocha --timeout 9999999 -r ts-node/register ./**/xcm/xcmTransferMoonbeam.test.ts",104 "benchMintingFee": "ts-node src/benchmarks/mintFee/benchmark.ts",105 "testApiConsts": "mocha --timeout 9999999 -r ts-node/register ./**/apiConsts.test.ts",106 "load": "mocha --timeout 9999999 -r ts-node/register './**/*.load.ts'",107 "loadTransfer": "ts-node src/transfer.nload.ts",108 "polkadot-types-fetch-metadata": "curl -H 'Content-Type: application/json' -d '{\"id\":\"1\", \"jsonrpc\":\"2.0\", \"method\": \"state_getMetadata\", \"params\":[]}' http://localhost:9933 > src/interfaces/metadata.json",109 "polkadot-types-from-defs": "ts-node ./node_modules/.bin/polkadot-types-from-defs --endpoint src/interfaces/metadata.json --input src/interfaces/ --package .",110 "polkadot-types-from-chain": "ts-node ./node_modules/.bin/polkadot-types-from-chain --endpoint src/interfaces/metadata.json --output src/interfaces/ --package .",111 "polkadot-types": "echo \"export default {}\" > src/interfaces/lookup.ts && yarn polkadot-types-fetch-metadata && yarn polkadot-types-from-defs && yarn polkadot-types-from-defs && yarn polkadot-types-from-chain"112 },113 "author": "",114 "license": "SEE LICENSE IN ../LICENSE",115 "homepage": "",116 "dependencies": {117 "@polkadot/api": "9.9.4",118 "@polkadot/util-crypto": "10.2.1",119 "chai-as-promised": "^7.1.1",120 "chai-like": "^1.1.1",121 "csv-writer": "^1.6.0",122 "find-process": "^1.4.7",123 "solc": "0.8.17",124 "web3": "^1.8.0"125 }126}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);
}