git.delta.rocks / unique-network / refs/commits / 1e2863e228ee

difftreelog

Merge pull request #780 from UniqueNetwork/feature/properties-for-ft-collections

ut-akuznetsov2022-12-16parents: #21ff2d2 #669456d.patch.diff
in: master

5 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -1222,7 +1222,8 @@
 		Ok(())
 	}
 
-	/// Set scouped collection property.
+	/// Set a scoped collection property, where the scope is a special prefix
+	/// prohibiting a user to change the property.
 	///
 	/// * `collection_id` - ID of the collection for which the property is being set.
 	/// * `scope` - Property scope.
@@ -1240,7 +1241,8 @@
 		Ok(())
 	}
 
-	/// Set scouped collection properties.
+	/// Set scoped collection properties, where the scope is a special prefix
+	/// prohibiting a user to change the properties.
 	///
 	/// * `collection_id` - ID of the collection for which the properties is being set.
 	/// * `scope` - Property scope.
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -18,7 +18,10 @@
 
 use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};
 use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget, CreateItemData};
-use pallet_common::{CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight};
+use pallet_common::{
+	CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
+	weights::WeightInfo as _,
+};
 use pallet_structure::Error as StructureError;
 use sp_runtime::ArithmeticError;
 use sp_std::{vec::Vec, vec};
@@ -53,14 +56,12 @@
 		<SelfWeightOf<T>>::burn_item()
 	}
 
-	fn set_collection_properties(_amount: u32) -> Weight {
-		// Error
-		Weight::zero()
+	fn set_collection_properties(amount: u32) -> Weight {
+		<pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)
 	}
 
-	fn delete_collection_properties(_amount: u32) -> Weight {
-		// Error
-		Weight::zero()
+	fn delete_collection_properties(amount: u32) -> Weight {
+		<pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)
 	}
 
 	fn set_token_properties(_amount: u32) -> Weight {
@@ -294,18 +295,28 @@
 
 	fn set_collection_properties(
 		&self,
-		_sender: T::CrossAccountId,
-		_property: Vec<Property>,
+		sender: T::CrossAccountId,
+		properties: Vec<Property>,
 	) -> DispatchResultWithPostInfo {
-		fail!(<Error<T>>::SettingPropertiesNotAllowed)
+		let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);
+
+		with_weight(
+			<Pallet<T>>::set_collection_properties(self, &sender, properties),
+			weight,
+		)
 	}
 
 	fn delete_collection_properties(
 		&self,
-		_sender: &T::CrossAccountId,
-		_property_keys: Vec<PropertyKey>,
+		sender: &T::CrossAccountId,
+		property_keys: Vec<PropertyKey>,
 	) -> DispatchResultWithPostInfo {
-		fail!(<Error<T>>::SettingPropertiesNotAllowed)
+		let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);
+
+		with_weight(
+			<Pallet<T>>::delete_collection_properties(self, sender, property_keys),
+			weight,
+		)
 	}
 
 	fn set_token_properties(
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -80,11 +80,11 @@
 
 use core::ops::Deref;
 use evm_coder::ToLog;
-use frame_support::{ensure};
+use frame_support::ensure;
 use pallet_evm::account::CrossAccountId;
 use up_data_structs::{
 	AccessMode, CollectionId, CollectionFlags, TokenId, CreateCollectionData,
-	mapping::TokenAddressMapping, budget::Budget,
+	mapping::TokenAddressMapping, budget::Budget, PropertyKey, Property,
 };
 use pallet_common::{
 	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
@@ -260,7 +260,25 @@
 		Ok(())
 	}
 
-	///Checks if collection has tokens. Return `true` if it has.
+	/// Add properties to the collection.
+	pub fn set_collection_properties(
+		collection: &FungibleHandle<T>,
+		sender: &T::CrossAccountId,
+		properties: Vec<Property>,
+	) -> DispatchResult {
+		<PalletCommon<T>>::set_collection_properties(collection, sender, properties)
+	}
+
+	/// Delete properties of the collection, associated with the provided keys.
+	pub fn delete_collection_properties(
+		collection: &FungibleHandle<T>,
+		sender: &T::CrossAccountId,
+		property_keys: Vec<PropertyKey>,
+	) -> DispatchResult {
+		<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)
+	}
+
+	/// Checks if collection has tokens. Return `true` if it has.
 	fn collection_has_tokens(collection_id: CollectionId) -> bool {
 		<TotalSupply<T>>::get(collection_id) != 0
 	}
modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -45,6 +45,7 @@
     "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 ./**/collectionProperties.test.ts ./**/tokenProperties.test.ts ./**/getPropertiesRpc.test.ts",
+    "testCollectionProperties": "mocha --timeout 9999999 -r ts-node/register ./**/collectionProperties.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",
modifiedtests/src/nesting/collectionProperties.test.tsdiffbeforeafterboth
before · tests/src/nesting/collectionProperties.test.ts
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([200n, 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 with the same size (${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    }));194195  [196    // TODO enable properties for FT collection in Substrate (release 040)197    // {mode: 'ft' as const, requiredPallets: []},198    {mode: 'nft' as const, requiredPallets: []},199    {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]}, 200  ].map(testCase =>201    itSub.ifWithPallets(`Modifying a collection property with different sizes correctly changes the consumed space (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {202      const propKey = 'tok-prop';203204      const collection = await helper[testCase.mode].mintCollection(alice);205      const originalSpace = await collection.getPropertiesConsumedSpace();206207      const initPropDataSize = 4096;208      const biggerPropDataSize = 5000;209      const smallerPropDataSize = 4000;210211      const initPropData = 'a'.repeat(initPropDataSize);212      const biggerPropData = 'b'.repeat(biggerPropDataSize);213      const smallerPropData = 'c'.repeat(smallerPropDataSize);214215      let consumedSpace;216      let expectedConsumedSpaceDiff;217218      await collection.setProperties(alice, [{key: propKey, value: initPropData}]);219      consumedSpace = await collection.getPropertiesConsumedSpace();220      expectedConsumedSpaceDiff = initPropDataSize - originalSpace;221      expect(consumedSpace).to.be.equal(originalSpace + expectedConsumedSpaceDiff);222223      await collection.setProperties(alice, [{key: propKey, value: biggerPropData}]);224      consumedSpace = await collection.getPropertiesConsumedSpace();225      expectedConsumedSpaceDiff = biggerPropDataSize - initPropDataSize;226      expect(consumedSpace).to.be.equal(initPropDataSize + expectedConsumedSpaceDiff);227228      await collection.setProperties(alice, [{key: propKey, value: smallerPropData}]);229      consumedSpace = await collection.getPropertiesConsumedSpace();230      expectedConsumedSpaceDiff = biggerPropDataSize - smallerPropDataSize;231      expect(consumedSpace).to.be.equal(biggerPropDataSize - expectedConsumedSpaceDiff);232    }));233});234  235describe('Negative Integration Test: Collection Properties', () => {236  let alice: IKeyringPair;237  let bob: IKeyringPair;238  239  before(async () => {240    await usingPlaygrounds(async (helper, privateKey) => {241      const donor = await privateKey({filename: __filename});242      [alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);243    });244  });245    246  async function testFailsSetPropertiesIfNotOwnerOrAdmin(collection: UniqueBaseCollection) {  247    await expect(collection.setProperties(bob, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]))248      .to.be.rejectedWith(/common\.NoPermission/);249  250    expect(await collection.getProperties()).to.be.empty;251  }252  253  itSub('Fails to set properties in a NFT collection if not its onwer/administrator', async ({helper}) =>  {254    await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.nft.mintCollection(alice));255  });256  257  itSub.ifWithPallets('Fails to set properties in a ReFungible collection if not its onwer/administrator', [Pallets.ReFungible], async ({helper}) => {258    await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.rft.mintCollection(alice));259  });260    261  async function testFailsSetPropertiesThatExeedLimits(collection: UniqueBaseCollection) {262    const spaceLimit = (await (collection.helper!.api! as any).query.common.collectionProperties(collection.collectionId)).spaceLimit.toNumber();263    264    // Mute the general tx parsing error, too many bytes to process265    {266      console.error = () => {};267      await expect(collection.setProperties(alice, [268        {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 9))},269      ])).to.be.rejected;270    }271  272    expect(await collection.getProperties(['electron'])).to.be.empty;273  274    await expect(collection.setProperties(alice, [275      {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 18))}, 276      {key: 'black_hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))}, 277    ])).to.be.rejectedWith(/common\.NoSpaceForProperty/);278  279    expect(await collection.getProperties(['electron', 'black_hole'])).to.be.empty;280  }281  282  itSub('Fails to set properties that exceed the limits (NFT)', async ({helper}) =>  {283    await testFailsSetPropertiesThatExeedLimits(await helper.nft.mintCollection(alice));284  });285  286  itSub.ifWithPallets('Fails to set properties that exceed the limits (ReFungible)', [Pallets.ReFungible], async ({helper}) => {287    await testFailsSetPropertiesThatExeedLimits(await helper.rft.mintCollection(alice));288  });289    290  async function testFailsSetMorePropertiesThanAllowed(collection: UniqueBaseCollection) {291    const propertiesToBeSet = [];292    for (let i = 0; i < 65; i++) {293      propertiesToBeSet.push({294        key: 'electron_' + i,295        value: Math.random() > 0.5 ? 'high' : 'low',296      });297    }298  299    await expect(collection.setProperties(alice, propertiesToBeSet)).300      to.be.rejectedWith(/common\.PropertyLimitReached/);301  302    expect(await collection.getProperties()).to.be.empty;303  }304  305  itSub('Fails to set more properties than it is allowed (NFT)', async ({helper}) =>  {306    await testFailsSetMorePropertiesThanAllowed(await helper.nft.mintCollection(alice));307  });308  309  itSub.ifWithPallets('Fails to set more properties than it is allowed (ReFungible)', [Pallets.ReFungible], async ({helper}) => {310    await testFailsSetMorePropertiesThanAllowed(await helper.rft.mintCollection(alice));311  });312    313  async function testFailsSetPropertiesWithInvalidNames(collection: UniqueBaseCollection) {314    const invalidProperties = [315      [{key: 'electron', value: 'negative'}, {key: 'string theory', value: 'understandable'}],316      [{key: 'Mr/Sandman', value: 'Bring me a gene'}],317      [{key: 'déjà vu', value: 'hmm...'}],318    ];319  320    for (let i = 0; i < invalidProperties.length; i++) {321      await expect(322        collection.setProperties(alice, invalidProperties[i]), 323        `on rejecting the new badly-named property #${i}`,324      ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);325    }326  327    await expect(328      collection.setProperties(alice, [{key: '', value: 'nothing must not exist'}]), 329      'on rejecting an unnamed property',330    ).to.be.rejectedWith(/common\.EmptyPropertyKey/);331  332    await expect(333      collection.setProperties(alice, [{key: 'CRISPR-Cas9', value: 'rewriting nature!'}]), 334      'on setting the correctly-but-still-badly-named property',335    ).to.be.fulfilled;336  337    const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat('CRISPR-Cas9').concat('');338  339    const properties = await collection.getProperties(keys);340    expect(properties).to.be.deep.equal([341      {key: 'CRISPR-Cas9', value: 'rewriting nature!'},342    ]);343  344    for (let i = 0; i < invalidProperties.length; i++) {345      await expect(346        collection.deleteProperties(alice, invalidProperties[i].map(propertySet => propertySet.key)), 347        `on trying to delete the non-existent badly-named property #${i}`,348      ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);349    }350  }351  352  itSub('Fails to set properties with invalid names (NFT)', async ({helper}) =>  {353    await testFailsSetPropertiesWithInvalidNames(await helper.nft.mintCollection(alice));354  });355  356  itSub.ifWithPallets('Fails to set properties with invalid names (ReFungible)', [Pallets.ReFungible], async ({helper}) => {357    await testFailsSetPropertiesWithInvalidNames(await helper.rft.mintCollection(alice));358  });359});360