difftreelog
refactor remove meta update permission
in: master
11 files changed
pallets/common/src/lib.rsdiffbeforeafterboth22use pallet_evm::account::CrossAccountId;22use pallet_evm::account::CrossAccountId;23use frame_support::{23use frame_support::{24 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},24 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},25 ensure, fail,25 ensure,26 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},26 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},27 BoundedVec,27 BoundedVec,28 weights::Pays,28 weights::Pays,29};29};30use pallet_evm::GasWeightMapping;30use pallet_evm::GasWeightMapping;31use up_data_structs::{31use up_data_structs::{32 COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionId, CreateItemData,32 COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionId, CreateItemData,33 MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, TokenId,33 MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, TokenId,34 CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT,34 CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT,35 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT,35 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT,36 CUSTOM_DATA_LIMIT, CollectionLimits, CreateCollectionData, SponsorshipState,36 CUSTOM_DATA_LIMIT, CollectionLimits, CreateCollectionData, SponsorshipState,136 Ok(())136 Ok(())137 }137 }138139 pub fn check_can_update_meta(140 &self,141 subject: &T::CrossAccountId,142 item_owner: &T::CrossAccountId,143 ) -> DispatchResult {144 match self.meta_update_permission {145 MetaUpdatePermission::ItemOwner => {146 ensure!(subject == item_owner, <Error<T>>::NoPermission);147 Ok(())148 }149 MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),150 MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),151 }152 }153}138}154139155#[frame_support::pallet]140#[frame_support::pallet]565 schema_version,550 schema_version,566 sponsorship,551 sponsorship,567 limits,552 limits,568 meta_update_permission,569 } = <CollectionById<T>>::get(collection)?;553 } = <CollectionById<T>>::get(collection)?;570554571 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)555 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)595 schema_version,579 schema_version,596 sponsorship,580 sponsorship,597 limits,581 limits,598 meta_update_permission,599 offchain_schema: <CollectionData<T>>::get((582 offchain_schema: <CollectionData<T>>::get((600 collection,583 collection,601 CollectionField::OffchainSchema,584 CollectionField::OffchainSchema,656 .limits639 .limits657 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))640 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))658 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,641 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,659 meta_update_permission: data.meta_update_permission.unwrap_or_default(),660 };642 };661643662 let mut collection_properties = up_data_structs::CollectionProperties::get();644 let mut collection_properties = up_data_structs::CollectionProperties::get();pallets/unique/src/benchmarking.rsdiffbeforeafterboth169 };169 };170 }: set_collection_limits(RawOrigin::Signed(caller.clone()), collection, cl)170 }: set_collection_limits(RawOrigin::Signed(caller.clone()), collection, cl)171172 set_meta_update_permission_flag {173 let caller: T::AccountId = account("caller", 0, SEED);174 let collection = create_nft_collection::<T>(caller.clone())?;175 }: _(RawOrigin::Signed(caller.clone()), collection, MetaUpdatePermission::Admin)176}171}177172pallets/unique/src/lib.rsdiffbeforeafterboth38 CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,38 CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,39 MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,39 MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,40 AccessMode, CreateItemData, CollectionLimits, CollectionId, CollectionMode, TokenId,40 AccessMode, CreateItemData, CollectionLimits, CollectionId, CollectionMode, TokenId,41 SchemaVersion, SponsorshipState, MetaUpdatePermission, CreateCollectionData,41 SchemaVersion, SponsorshipState, CreateCollectionData,42 CreateItemExData, budget, CollectionField, Property, PropertyKey, PropertyKeyPermission,42 CreateItemExData, budget, CollectionField, Property, PropertyKey, PropertyKeyPermission,43};43};44use pallet_evm::account::CrossAccountId;44use pallet_evm::account::CrossAccountId;45use pallet_common::{45use pallet_common::{46 CollectionHandle, Pallet as PalletCommon, Error as CommonError, CommonWeightInfo,46 CollectionHandle, Pallet as PalletCommon, CommonWeightInfo,47 dispatch::dispatch_call, dispatch::CollectionDispatch,47 dispatch::dispatch_call, dispatch::CollectionDispatch,48};48};4949927 dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))927 dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))928 }928 }929930 /// Set meta_update_permission value for particular collection931 ///932 /// # Permissions933 ///934 /// * Collection Owner.935 ///936 /// # Arguments937 ///938 /// * collection_id: ID of the collection.939 ///940 /// * value: New flag value.941 #[weight = <SelfWeightOf<T>>::set_meta_update_permission_flag()]942 #[transactional]943 pub fn set_meta_update_permission_flag(origin, collection_id: CollectionId, value: MetaUpdatePermission) -> DispatchResult {944 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);945 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;946947 ensure!(948 target_collection.meta_update_permission != MetaUpdatePermission::None,949 <CommonError<T>>::MetadataFlagFrozen,950 );951 target_collection.check_is_owner(&sender)?;952953 target_collection.meta_update_permission = value;954955 target_collection.save()956 }957929958 /// Set schema standard930 /// Set schema standard959 /// ImageURL931 /// ImageURLpallets/unique/src/weights.rsdiffbeforeafterboth49 fn set_const_on_chain_schema(b: u32, ) -> Weight;49 fn set_const_on_chain_schema(b: u32, ) -> Weight;50 fn set_schema_version() -> Weight;50 fn set_schema_version() -> Weight;51 fn set_collection_limits() -> Weight;51 fn set_collection_limits() -> Weight;52 fn set_meta_update_permission_flag() -> Weight;53}52}545355/// Weights for pallet_unique using the Substrate node and recommended hardware.54/// Weights for pallet_unique using the Substrate node and recommended hardware.170 .saturating_add(T::DbWeight::get().reads(1 as Weight))169 .saturating_add(T::DbWeight::get().reads(1 as Weight))171 .saturating_add(T::DbWeight::get().writes(1 as Weight))170 .saturating_add(T::DbWeight::get().writes(1 as Weight))172 }171 }173 // Storage: Common CollectionById (r:1 w:1)174 fn set_meta_update_permission_flag() -> Weight {175 (7_214_000 as Weight)176 .saturating_add(T::DbWeight::get().reads(1 as Weight))177 .saturating_add(T::DbWeight::get().writes(1 as Weight))178 }179}172}180173181// For backwards compatibility and tests174// For backwards compatibility and tests295 .saturating_add(RocksDbWeight::get().reads(1 as Weight))288 .saturating_add(RocksDbWeight::get().reads(1 as Weight))296 .saturating_add(RocksDbWeight::get().writes(1 as Weight))289 .saturating_add(RocksDbWeight::get().writes(1 as Weight))297 }290 }298 // Storage: Common CollectionById (r:1 w:1)299 fn set_meta_update_permission_flag() -> Weight {300 (7_214_000 as Weight)301 .saturating_add(RocksDbWeight::get().reads(1 as Weight))302 .saturating_add(RocksDbWeight::get().writes(1 as Weight))303 }304}291}305292primitives/data-structs/src/lib.rsdiffbeforeafterboth308 #[version(..2)]308 #[version(..2)]309 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,309 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,310310311 #[version(..2)]311 pub meta_update_permission: MetaUpdatePermission,312 pub meta_update_permission: MetaUpdatePermission,312}313}313314327 pub sponsorship: SponsorshipState<AccountId>,328 pub sponsorship: SponsorshipState<AccountId>,328 pub limits: CollectionLimits,329 pub limits: CollectionLimits,329 pub const_on_chain_schema: Vec<u8>,330 pub const_on_chain_schema: Vec<u8>,330 pub meta_update_permission: MetaUpdatePermission,331 pub token_property_permissions: Vec<PropertyKeyPermission>,331 pub token_property_permissions: Vec<PropertyKeyPermission>,332 pub properties: Vec<Property>,332 pub properties: Vec<Property>,333}333}353 pub pending_sponsor: Option<AccountId>,353 pub pending_sponsor: Option<AccountId>,354 pub limits: Option<CollectionLimits>,354 pub limits: Option<CollectionLimits>,355 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,355 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,356 pub meta_update_permission: Option<MetaUpdatePermission>,357 pub token_property_permissions: CollectionPropertiesPermissionsVec,356 pub token_property_permissions: CollectionPropertiesPermissionsVec,358 pub properties: CollectionPropertiesVec,357 pub properties: CollectionPropertiesVec,359}358}493}492}494493495#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]494#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]496#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]497pub enum MetaUpdatePermission {495pub enum MetaUpdatePermission {498 ItemOwner,496 ItemOwner,499 Admin,497 Admin,500 None,498 None,501}499}502503impl Default for MetaUpdatePermission {504 fn default() -> Self {505 Self::ItemOwner506 }507}508500509#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]501#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]510#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]502#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]runtime/tests/src/tests.rsdiffbeforeafterboth18use crate::{Test, TestCrossAccountId, CollectionCreationPrice, Origin, Unique, new_test_ext};18use crate::{Test, TestCrossAccountId, CollectionCreationPrice, Origin, Unique, new_test_ext};19use up_data_structs::{19use up_data_structs::{20 COLLECTION_NUMBER_LIMIT, CollectionId, CreateItemData, CreateFungibleData, CreateNftData,20 COLLECTION_NUMBER_LIMIT, CollectionId, CreateItemData, CreateFungibleData, CreateNftData,21 CreateReFungibleData, MAX_DECIMAL_POINTS, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission,21 CreateReFungibleData, MAX_DECIMAL_POINTS, COLLECTION_ADMINS_LIMIT,22 TokenId, MAX_TOKEN_OWNERSHIP, CreateCollectionData, CollectionField, SchemaVersion,22 TokenId, MAX_TOKEN_OWNERSHIP, CreateCollectionData, CollectionField, SchemaVersion,23 CollectionMode, AccessMode,23 CollectionMode, AccessMode,24};24};2471 });2471 });2472}2472}24732474#[test]2475fn set_variable_meta_flag_after_freeze() {2476 new_test_ext().execute_with(|| {2477 // default_limits();24782479 let collection_id =2480 create_test_collection_for_owner(&CollectionMode::NFT, 2, CollectionId(1));24812482 let origin2 = Origin::signed(2);24832484 assert_ok!(Unique::set_meta_update_permission_flag(2485 origin2.clone(),2486 collection_id,2487 MetaUpdatePermission::None,2488 ));2489 assert_noop!(2490 Unique::set_meta_update_permission_flag(2491 origin2.clone(),2492 collection_id,2493 MetaUpdatePermission::Admin2494 ),2495 CommonError::<Test>::MetadataFlagFrozen2496 );2497 });2498}249924732500#[test]2474#[test]2501fn collection_transfer_flag_works_neg() {2475fn collection_transfer_flag_works_neg() {tests/src/createCollection.test.tsdiffbeforeafterboth74 accountTokenOwnershipLimit: 3,74 accountTokenOwnershipLimit: 3,75 },75 },76 constOnChainSchema: '0x333333',76 constOnChainSchema: '0x333333',77 metaUpdatePermission: 'Admin',78 });77 });79 const events = await submitTransactionAsync(alice, tx);78 const events = await submitTransactionAsync(alice, tx);80 const result = getCreateCollectionResult(events);79 const result = getCreateCollectionResult(events);91 expect(collection.sponsorship.asUnconfirmed.toString()).to.equal(bob.address);90 expect(collection.sponsorship.asUnconfirmed.toString()).to.equal(bob.address);92 expect(collection.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.equal(3);91 expect(collection.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.equal(3);93 expect(collection.constOnChainSchema.toString()).to.equal('0x333333');92 expect(collection.constOnChainSchema.toString()).to.equal('0x333333');94 expect(collection.metaUpdatePermission.isAdmin).to.be.true;95 });93 });96 });94 });97});95});tests/src/eth/nonFungible.test.tsdiffbeforeafterboth15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.161617import privateKey from '../substrate/privateKey';17import privateKey from '../substrate/privateKey';18import {approveExpectSuccess, burnItemExpectSuccess, createCollectionExpectSuccess, createItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess, UNIQUE, setMetadataUpdatePermissionFlagExpectSuccess} from '../util/helpers';18import {approveExpectSuccess, burnItemExpectSuccess, createCollectionExpectSuccess, createItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess, UNIQUE} from '../util/helpers';19import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, transferBalanceToEth} from './util/helpers';19import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, transferBalanceToEth} from './util/helpers';20import nonFungibleAbi from './nonFungibleAbi.json';20import nonFungibleAbi from './nonFungibleAbi.json';21import {expect} from 'chai';21import {expect} from 'chai';tests/src/eth/proxy/nonFungibleProxy.test.tsdiffbeforeafterboth15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.161617import privateKey from '../../substrate/privateKey';17import privateKey from '../../substrate/privateKey';18import {createCollectionExpectSuccess, createItemExpectSuccess, setMetadataUpdatePermissionFlagExpectSuccess} from '../../util/helpers';18import {createCollectionExpectSuccess, createItemExpectSuccess} from '../../util/helpers';19import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents} from '../util/helpers';19import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents} from '../util/helpers';20import nonFungibleAbi from '../nonFungibleAbi.json';20import nonFungibleAbi from '../nonFungibleAbi.json';21import {expect} from 'chai';21import {expect} from 'chai';tests/src/nesting/migration-check.test.tsdiffbeforeafterboth37 accountTokenOwnershipLimit: 3,37 accountTokenOwnershipLimit: 3,38 },38 },39 constOnChainSchema: '0x333333',39 constOnChainSchema: '0x333333',40 metaUpdatePermission: 'Admin',41 });40 });42 const events = await submitTransactionAsync(alice, tx);41 const events = await submitTransactionAsync(alice, tx);43 const result = getCreateCollectionResult(events);42 const result = getCreateCollectionResult(events);tests/src/util/helpers.tsdiffbeforeafterboth650 });650 });651}651}652653export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {654655 await usingApi(async (api) => {656 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);657 const events = await submitTransactionAsync(sender, tx);658 const result = getGenericResult(events);659660 expect(result.success).to.be.true;661 });662}663664export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {665666 await usingApi(async (api) => {667 const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);668 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;669 const result = getGenericResult(events);670671 expect(result.success).to.be.false;672 });673}674652675export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {653export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {676 await usingApi(async (api) => {654 await usingApi(async (api) => {