git.delta.rocks / unique-network / refs/commits / 04a22c8dcea1

difftreelog

refactor remove meta update permission

Daniel Shiposha2022-05-15parent: #07f2d6c.patch.diff
in: master

11 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -22,7 +22,7 @@
 use pallet_evm::account::CrossAccountId;
 use frame_support::{
 	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},
-	ensure, fail,
+	ensure,
 	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},
 	BoundedVec,
 	weights::Pays,
@@ -30,7 +30,7 @@
 use pallet_evm::GasWeightMapping;
 use up_data_structs::{
 	COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionId, CreateItemData,
-	MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, TokenId,
+	MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, TokenId,
 	CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT,
 	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT,
 	CUSTOM_DATA_LIMIT, CollectionLimits, CreateCollectionData, SponsorshipState,
@@ -134,21 +134,6 @@
 			<Error<T>>::AddressNotInAllowlist
 		);
 		Ok(())
-	}
-
-	pub fn check_can_update_meta(
-		&self,
-		subject: &T::CrossAccountId,
-		item_owner: &T::CrossAccountId,
-	) -> DispatchResult {
-		match self.meta_update_permission {
-			MetaUpdatePermission::ItemOwner => {
-				ensure!(subject == item_owner, <Error<T>>::NoPermission);
-				Ok(())
-			}
-			MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),
-			MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),
-		}
 	}
 }
 
@@ -565,7 +550,6 @@
 			schema_version,
 			sponsorship,
 			limits,
-			meta_update_permission,
 		} = <CollectionById<T>>::get(collection)?;
 
 		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)
@@ -595,7 +579,6 @@
 			schema_version,
 			sponsorship,
 			limits,
-			meta_update_permission,
 			offchain_schema: <CollectionData<T>>::get((
 				collection,
 				CollectionField::OffchainSchema,
@@ -656,7 +639,6 @@
 				.limits
 				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))
 				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,
-			meta_update_permission: data.meta_update_permission.unwrap_or_default(),
 		};
 
 		let mut collection_properties = up_data_structs::CollectionProperties::get();
modifiedpallets/unique/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/unique/src/benchmarking.rs
+++ b/pallets/unique/src/benchmarking.rs
@@ -168,9 +168,4 @@
 			nesting_rule: None,
 		};
 	}: set_collection_limits(RawOrigin::Signed(caller.clone()), collection, cl)
-
-	set_meta_update_permission_flag {
-		let caller: T::AccountId = account("caller", 0, SEED);
-		let collection = create_nft_collection::<T>(caller.clone())?;
-	}: _(RawOrigin::Signed(caller.clone()), collection, MetaUpdatePermission::Admin)
 }
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -38,12 +38,12 @@
 	CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,
 	MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
 	AccessMode, CreateItemData, CollectionLimits, CollectionId, CollectionMode, TokenId,
-	SchemaVersion, SponsorshipState, MetaUpdatePermission, CreateCollectionData,
+	SchemaVersion, SponsorshipState, CreateCollectionData,
 	CreateItemExData, budget, CollectionField, Property, PropertyKey, PropertyKeyPermission,
 };
 use pallet_evm::account::CrossAccountId;
 use pallet_common::{
-	CollectionHandle, Pallet as PalletCommon, Error as CommonError, CommonWeightInfo,
+	CollectionHandle, Pallet as PalletCommon, CommonWeightInfo,
 	dispatch::dispatch_call, dispatch::CollectionDispatch,
 };
 
@@ -925,34 +925,6 @@
 			let budget = budget::Value::new(2);
 
 			dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))
-		}
-
-		/// Set meta_update_permission value for particular collection
-		///
-		/// # Permissions
-		///
-		/// * Collection Owner.
-		///
-		/// # Arguments
-		///
-		/// * collection_id: ID of the collection.
-		///
-		/// * value: New flag value.
-		#[weight = <SelfWeightOf<T>>::set_meta_update_permission_flag()]
-		#[transactional]
-		pub fn set_meta_update_permission_flag(origin, collection_id: CollectionId, value: MetaUpdatePermission) -> DispatchResult {
-			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
-
-			ensure!(
-				target_collection.meta_update_permission != MetaUpdatePermission::None,
-				<CommonError<T>>::MetadataFlagFrozen,
-			);
-			target_collection.check_is_owner(&sender)?;
-
-			target_collection.meta_update_permission = value;
-
-			target_collection.save()
 		}
 
 		/// Set schema standard
modifiedpallets/unique/src/weights.rsdiffbeforeafterboth
--- a/pallets/unique/src/weights.rs
+++ b/pallets/unique/src/weights.rs
@@ -49,7 +49,6 @@
 	fn set_const_on_chain_schema(b: u32, ) -> Weight;
 	fn set_schema_version() -> Weight;
 	fn set_collection_limits() -> Weight;
-	fn set_meta_update_permission_flag() -> Weight;
 }
 
 /// Weights for pallet_unique using the Substrate node and recommended hardware.
@@ -167,12 +166,6 @@
 	// Storage: Common CollectionById (r:1 w:1)
 	fn set_collection_limits() -> Weight {
 		(15_339_000 as Weight)
-			.saturating_add(T::DbWeight::get().reads(1 as Weight))
-			.saturating_add(T::DbWeight::get().writes(1 as Weight))
-	}
-	// Storage: Common CollectionById (r:1 w:1)
-	fn set_meta_update_permission_flag() -> Weight {
-		(7_214_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(1 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
@@ -292,12 +285,6 @@
 	// Storage: Common CollectionById (r:1 w:1)
 	fn set_collection_limits() -> Weight {
 		(15_339_000 as Weight)
-			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
-			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
-	}
-	// Storage: Common CollectionById (r:1 w:1)
-	fn set_meta_update_permission_flag() -> Weight {
-		(7_214_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -308,6 +308,7 @@
 	#[version(..2)]
 	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,
 
+	#[version(..2)]
 	pub meta_update_permission: MetaUpdatePermission,
 }
 
@@ -327,7 +328,6 @@
 	pub sponsorship: SponsorshipState<AccountId>,
 	pub limits: CollectionLimits,
 	pub const_on_chain_schema: Vec<u8>,
-	pub meta_update_permission: MetaUpdatePermission,
 	pub token_property_permissions: Vec<PropertyKeyPermission>,
 	pub properties: Vec<Property>,
 }
@@ -353,7 +353,6 @@
 	pub pending_sponsor: Option<AccountId>,
 	pub limits: Option<CollectionLimits>,
 	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,
-	pub meta_update_permission: Option<MetaUpdatePermission>,
 	pub token_property_permissions: CollectionPropertiesPermissionsVec,
 	pub properties: CollectionPropertiesVec,
 }
@@ -493,17 +492,10 @@
 }
 
 #[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
 pub enum MetaUpdatePermission {
 	ItemOwner,
 	Admin,
 	None,
-}
-
-impl Default for MetaUpdatePermission {
-	fn default() -> Self {
-		Self::ItemOwner
-	}
 }
 
 #[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
modifiedruntime/tests/src/tests.rsdiffbeforeafterboth
--- a/runtime/tests/src/tests.rs
+++ b/runtime/tests/src/tests.rs
@@ -18,7 +18,7 @@
 use crate::{Test, TestCrossAccountId, CollectionCreationPrice, Origin, Unique, new_test_ext};
 use up_data_structs::{
 	COLLECTION_NUMBER_LIMIT, CollectionId, CreateItemData, CreateFungibleData, CreateNftData,
-	CreateReFungibleData, MAX_DECIMAL_POINTS, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission,
+	CreateReFungibleData, MAX_DECIMAL_POINTS, COLLECTION_ADMINS_LIMIT,
 	TokenId, MAX_TOKEN_OWNERSHIP, CreateCollectionData, CollectionField, SchemaVersion,
 	CollectionMode, AccessMode,
 };
@@ -2467,32 +2467,6 @@
 		assert_eq!(
 			<pallet_nonfungible::AccountBalance<Test>>::get((collection_id, account(2))),
 			1
-		);
-	});
-}
-
-#[test]
-fn set_variable_meta_flag_after_freeze() {
-	new_test_ext().execute_with(|| {
-		// default_limits();
-
-		let collection_id =
-			create_test_collection_for_owner(&CollectionMode::NFT, 2, CollectionId(1));
-
-		let origin2 = Origin::signed(2);
-
-		assert_ok!(Unique::set_meta_update_permission_flag(
-			origin2.clone(),
-			collection_id,
-			MetaUpdatePermission::None,
-		));
-		assert_noop!(
-			Unique::set_meta_update_permission_flag(
-				origin2.clone(),
-				collection_id,
-				MetaUpdatePermission::Admin
-			),
-			CommonError::<Test>::MetadataFlagFrozen
 		);
 	});
 }
modifiedtests/src/createCollection.test.tsdiffbeforeafterboth
--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -74,7 +74,6 @@
           accountTokenOwnershipLimit: 3,
         },
         constOnChainSchema: '0x333333',
-        metaUpdatePermission: 'Admin',
       });
       const events = await submitTransactionAsync(alice, tx);
       const result = getCreateCollectionResult(events);
@@ -91,7 +90,6 @@
       expect(collection.sponsorship.asUnconfirmed.toString()).to.equal(bob.address);
       expect(collection.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.equal(3);
       expect(collection.constOnChainSchema.toString()).to.equal('0x333333');
-      expect(collection.metaUpdatePermission.isAdmin).to.be.true;
     });
   });
 });
modifiedtests/src/eth/nonFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -15,7 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import privateKey from '../substrate/privateKey';
-import {approveExpectSuccess, burnItemExpectSuccess, createCollectionExpectSuccess, createItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess, UNIQUE, setMetadataUpdatePermissionFlagExpectSuccess} from '../util/helpers';
+import {approveExpectSuccess, burnItemExpectSuccess, createCollectionExpectSuccess, createItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess, UNIQUE} from '../util/helpers';
 import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, transferBalanceToEth} from './util/helpers';
 import nonFungibleAbi from './nonFungibleAbi.json';
 import {expect} from 'chai';
modifiedtests/src/eth/proxy/nonFungibleProxy.test.tsdiffbeforeafterboth
--- a/tests/src/eth/proxy/nonFungibleProxy.test.ts
+++ b/tests/src/eth/proxy/nonFungibleProxy.test.ts
@@ -15,7 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import privateKey from '../../substrate/privateKey';
-import {createCollectionExpectSuccess, createItemExpectSuccess, setMetadataUpdatePermissionFlagExpectSuccess} from '../../util/helpers';
+import {createCollectionExpectSuccess, createItemExpectSuccess} from '../../util/helpers';
 import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents} from '../util/helpers';
 import nonFungibleAbi from '../nonFungibleAbi.json';
 import {expect} from 'chai';
modifiedtests/src/nesting/migration-check.test.tsdiffbeforeafterboth
before · tests/src/nesting/migration-check.test.ts
1import {expect} from 'chai';2import privateKey from '../substrate/privateKey';3import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';4import {getCreateCollectionResult} from '../util/helpers';5import {IKeyringPair} from '@polkadot/types/types';6import {strToUTF16} from '../util/util';7import waitNewBlocks from '../substrate/wait-new-blocks';8// Used for polkadot-launch signalling9import find from 'find-process';1011// todo un-skip for migrations12describe.skip('Migration testing for pallet-common', () => {13  let alice: IKeyringPair;1415  before(async() => {16    await usingApi(async () => {17      alice = privateKey('//Alice');18    });19  });2021  it('Preserves collection settings after migration', async () => {22    let oldVersion: number;23    let collectionId: number;24    let collectionOld: any;2526    await usingApi(async api => {27      // Create a collection for comparison before and after the upgrade28      const tx = api.tx.unique.createCollectionEx({29        mode: 'NFT',30        access: 'AllowList',31        name: strToUTF16('Mojave Pictures'),32        description: strToUTF16('$2.2 billion power plant!'),33        tokenPrefix: '0x0002030',34        offchainSchema: '0x111111',35        schemaVersion: 'Unique',36        limits: {37          accountTokenOwnershipLimit: 3,38        },39        constOnChainSchema: '0x333333',40        metaUpdatePermission: 'Admin',41      });42      const events = await submitTransactionAsync(alice, tx);43      const result = getCreateCollectionResult(events);44      collectionId = result.collectionId;4546      // Get the pre-upgrade collection info47      collectionOld = (await api.query.common.collectionById(collectionId)).toJSON();4849      // Get the pre-upgrade spec version50      oldVersion = (api.consts.system.version.toJSON() as any).specVersion;51    });5253    console.log(`Now waiting for the parachain upgrade from ${oldVersion!}...`);5455    let newVersion = oldVersion!;56    let connectionFailCounter = 0;5758    // Cooperate with polkadot-launch if it's running (assuming custom name change to 'polkadot-launch'), and send a custom signal59    find('name', 'polkadot-launch', true).then((list) => {60      for (const proc of list) {61        process.kill(proc.pid, 'SIGUSR1');62      }63    });6465    // And wait for the parachain upgrade66    {67      // Catch warnings like 'RPC methods not decorated' and keep the 'waiting' message in front68      const stdlog = console.warn.bind(console);69      let warnCount = 0;70      console.warn = function(...args){71        if (arguments.length <= 2 || !args[2].includes('RPC methods not decorated')) {72          warnCount++;73          stdlog.apply(console, args as any);74        }75      };7677      let oldWarnCount = 0;78      while (newVersion == oldVersion! && connectionFailCounter < 2) {79        try {80          await usingApi(async api => {81            await waitNewBlocks(api);82            newVersion = (api.consts.system.version.toJSON() as any).specVersion;83            if (warnCount > oldWarnCount) {84              console.log(`Still waiting for the parachain upgrade from ${oldVersion!}...`);85              oldWarnCount = warnCount;86            }87            await new Promise(resolve => setTimeout(resolve, 6000));88          });89        } catch (_) {90          connectionFailCounter++;91          await new Promise(resolve => setTimeout(resolve, 12000));92        }93      }94    }9596    await usingApi(async api => {97      const collectionNew = (await api.query.common.collectionById(collectionId)).toJSON() as any;9899      // Make sure the extra fields are what they should be100      const constOnChainSchema = await api.query.common.collectionData(collectionId, 'ConstOnChainSchema');101      const offchainSchema = await api.query.common.collectionData(collectionId, 'OffchainSchema');102103      expect(constOnChainSchema.toHex()).to.be.deep.equal(collectionOld.constOnChainSchema);104      expect(offchainSchema.toHex()).to.be.deep.equal(collectionOld.offchainSchema);105      expect(collectionNew).to.have.nested.property('limits.nestingRule');106107      // Get rid of extra fields to perform comparison on the rest of the collection108      delete collectionNew.limits.nestingRule;109      delete collectionOld.constOnChainSchema;110      delete collectionOld.offchainSchema;111112      expect(collectionNew).to.be.deep.equal(collectionOld);113    });114  });115});
after · tests/src/nesting/migration-check.test.ts
1import {expect} from 'chai';2import privateKey from '../substrate/privateKey';3import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';4import {getCreateCollectionResult} from '../util/helpers';5import {IKeyringPair} from '@polkadot/types/types';6import {strToUTF16} from '../util/util';7import waitNewBlocks from '../substrate/wait-new-blocks';8// Used for polkadot-launch signalling9import find from 'find-process';1011// todo un-skip for migrations12describe.skip('Migration testing for pallet-common', () => {13  let alice: IKeyringPair;1415  before(async() => {16    await usingApi(async () => {17      alice = privateKey('//Alice');18    });19  });2021  it('Preserves collection settings after migration', async () => {22    let oldVersion: number;23    let collectionId: number;24    let collectionOld: any;2526    await usingApi(async api => {27      // Create a collection for comparison before and after the upgrade28      const tx = api.tx.unique.createCollectionEx({29        mode: 'NFT',30        access: 'AllowList',31        name: strToUTF16('Mojave Pictures'),32        description: strToUTF16('$2.2 billion power plant!'),33        tokenPrefix: '0x0002030',34        offchainSchema: '0x111111',35        schemaVersion: 'Unique',36        limits: {37          accountTokenOwnershipLimit: 3,38        },39        constOnChainSchema: '0x333333',40      });41      const events = await submitTransactionAsync(alice, tx);42      const result = getCreateCollectionResult(events);43      collectionId = result.collectionId;4445      // Get the pre-upgrade collection info46      collectionOld = (await api.query.common.collectionById(collectionId)).toJSON();4748      // Get the pre-upgrade spec version49      oldVersion = (api.consts.system.version.toJSON() as any).specVersion;50    });5152    console.log(`Now waiting for the parachain upgrade from ${oldVersion!}...`);5354    let newVersion = oldVersion!;55    let connectionFailCounter = 0;5657    // Cooperate with polkadot-launch if it's running (assuming custom name change to 'polkadot-launch'), and send a custom signal58    find('name', 'polkadot-launch', true).then((list) => {59      for (const proc of list) {60        process.kill(proc.pid, 'SIGUSR1');61      }62    });6364    // And wait for the parachain upgrade65    {66      // Catch warnings like 'RPC methods not decorated' and keep the 'waiting' message in front67      const stdlog = console.warn.bind(console);68      let warnCount = 0;69      console.warn = function(...args){70        if (arguments.length <= 2 || !args[2].includes('RPC methods not decorated')) {71          warnCount++;72          stdlog.apply(console, args as any);73        }74      };7576      let oldWarnCount = 0;77      while (newVersion == oldVersion! && connectionFailCounter < 2) {78        try {79          await usingApi(async api => {80            await waitNewBlocks(api);81            newVersion = (api.consts.system.version.toJSON() as any).specVersion;82            if (warnCount > oldWarnCount) {83              console.log(`Still waiting for the parachain upgrade from ${oldVersion!}...`);84              oldWarnCount = warnCount;85            }86            await new Promise(resolve => setTimeout(resolve, 6000));87          });88        } catch (_) {89          connectionFailCounter++;90          await new Promise(resolve => setTimeout(resolve, 12000));91        }92      }93    }9495    await usingApi(async api => {96      const collectionNew = (await api.query.common.collectionById(collectionId)).toJSON() as any;9798      // Make sure the extra fields are what they should be99      const constOnChainSchema = await api.query.common.collectionData(collectionId, 'ConstOnChainSchema');100      const offchainSchema = await api.query.common.collectionData(collectionId, 'OffchainSchema');101102      expect(constOnChainSchema.toHex()).to.be.deep.equal(collectionOld.constOnChainSchema);103      expect(offchainSchema.toHex()).to.be.deep.equal(collectionOld.offchainSchema);104      expect(collectionNew).to.have.nested.property('limits.nestingRule');105106      // Get rid of extra fields to perform comparison on the rest of the collection107      delete collectionNew.limits.nestingRule;108      delete collectionOld.constOnChainSchema;109      delete collectionOld.offchainSchema;110111      expect(collectionNew).to.be.deep.equal(collectionOld);112    });113  });114});
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -650,28 +650,6 @@
   });
 }
 
-export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {
-
-  await usingApi(async (api) => {
-    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);
-    const events = await submitTransactionAsync(sender, tx);
-    const result = getGenericResult(events);
-
-    expect(result.success).to.be.true;
-  });
-}
-
-export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {
-
-  await usingApi(async (api) => {
-    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);
-    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
-    const result = getGenericResult(events);
-
-    expect(result.success).to.be.false;
-  });
-}
-
 export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {
   await usingApi(async (api) => {
     const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);