difftreelog
Merge pull request #414 from UniqueNetwork/feature/prop-check-root-owner
in: master
Feature/prop check root owner
9 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -1311,12 +1311,14 @@
sender: T::CrossAccountId,
token_id: TokenId,
property: Vec<Property>,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo;
fn delete_token_properties(
&self,
sender: T::CrossAccountId,
token_id: TokenId,
property_keys: Vec<PropertyKey>,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo;
fn set_token_property_permissions(
&self,
@@ -1361,7 +1363,7 @@
sender: T::CrossAccountId,
from: (CollectionId, TokenId),
under: TokenId,
- budget: &dyn Budget,
+ nesting_budget: &dyn Budget,
) -> DispatchResult;
fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -298,6 +298,7 @@
_sender: T::CrossAccountId,
_token_id: TokenId,
_property: Vec<Property>,
+ _nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
fail!(<Error<T>>::SettingPropertiesNotAllowed)
}
@@ -315,6 +316,7 @@
_sender: T::CrossAccountId,
_token_id: TokenId,
_property_keys: Vec<PropertyKey>,
+ _nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
fail!(<Error<T>>::SettingPropertiesNotAllowed)
}
@@ -324,7 +326,7 @@
_sender: <T>::CrossAccountId,
_from: (CollectionId, TokenId),
_under: TokenId,
- _budget: &dyn Budget,
+ _nesting_budget: &dyn Budget,
) -> sp_runtime::DispatchResult {
fail!(<Error<T>>::FungibleDisallowsNesting)
}
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -183,7 +183,7 @@
value: property_value(),
}).collect::<Vec<_>>();
let item = create_max_item(&collection, &owner, owner.clone())?;
- }: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props, false)?}
+ }: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props, false, &Unlimited)?}
delete_token_properties {
let b in 0..MAX_PROPERTIES_PER_ITEM;
@@ -205,7 +205,7 @@
value: property_value(),
}).collect::<Vec<_>>();
let item = create_max_item(&collection, &owner, owner.clone())?;
- <Pallet<T>>::set_token_properties(&collection, &owner, item, props, false)?;
+ <Pallet<T>>::set_token_properties(&collection, &owner, item, props, false, &Unlimited)?;
let to_delete = (0..b).map(|k| property_key(k as usize)).collect::<Vec<_>>();
- }: {<Pallet<T>>::delete_token_properties(&collection, &owner, item, to_delete)?}
+ }: {<Pallet<T>>::delete_token_properties(&collection, &owner, item, to_delete, &Unlimited)?}
}
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -220,11 +220,19 @@
sender: T::CrossAccountId,
token_id: TokenId,
properties: Vec<Property>,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);
with_weight(
- <Pallet<T>>::set_token_properties(self, &sender, token_id, properties, false),
+ <Pallet<T>>::set_token_properties(
+ self,
+ &sender,
+ token_id,
+ properties.into_iter(),
+ false,
+ nesting_budget,
+ ),
weight,
)
}
@@ -234,11 +242,18 @@
sender: T::CrossAccountId,
token_id: TokenId,
property_keys: Vec<PropertyKey>,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);
with_weight(
- <Pallet<T>>::delete_token_properties(self, &sender, token_id, property_keys),
+ <Pallet<T>>::delete_token_properties(
+ self,
+ &sender,
+ token_id,
+ property_keys.into_iter(),
+ nesting_budget,
+ ),
weight,
)
}
@@ -368,9 +383,9 @@
sender: T::CrossAccountId,
from: (CollectionId, TokenId),
under: TokenId,
- budget: &dyn Budget,
+ nesting_budget: &dyn Budget,
) -> sp_runtime::DispatchResult {
- <Pallet<T>>::check_nesting(self, sender, from, under, budget)
+ <Pallet<T>>::check_nesting(self, sender, from, under, nesting_budget)
}
fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId)) {
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -82,12 +82,16 @@
.map_err(|_| "key too long")?;
let value = value.try_into().map_err(|_| "value too long")?;
+ let nesting_budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
<Pallet<T>>::set_token_property(
self,
&caller,
TokenId(token_id),
Property { key, value },
- false,
+ &nesting_budget,
)
.map_err(dispatch_to_evm::<T>)
}
@@ -99,7 +103,11 @@
.try_into()
.map_err(|_| "key too long")?;
- <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key)
+ let nesting_budget = self
+ .recorder
+ .weight_calls_budget(<StructureWeight<T>>::find_parent());
+
+ <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)
.map_err(dispatch_to_evm::<T>)
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth28use up_data_structs::{28use up_data_structs::{29 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,29 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,30 mapping::TokenAddressMapping, budget::Budget, Property, PropertyPermission, PropertyKey,30 mapping::TokenAddressMapping, budget::Budget, Property, PropertyPermission, PropertyKey,31 PropertyKeyPermission, Properties, PropertyScope, TrySetProperty, TokenChild, AuxPropertyValue,31 PropertyValue, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty, TokenChild,32 AuxPropertyValue,32};33};33use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};34use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};480 })481 })481 }482 }482483484 #[transactional]483 pub fn set_token_property(485 fn modify_token_properties(484 collection: &NonfungibleHandle<T>,486 collection: &NonfungibleHandle<T>,485 sender: &T::CrossAccountId,487 sender: &T::CrossAccountId,486 token_id: TokenId,488 token_id: TokenId,487 property: Property,489 properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,488 is_token_create: bool,490 is_token_create: bool,491 nesting_budget: &dyn Budget,489 ) -> DispatchResult {492 ) -> DispatchResult {493 let mut collection_admin_status = None;494 let mut token_owner_result = None;495496 let mut is_collection_admin =497 || *collection_admin_status.get_or_insert_with(|| collection.is_owner_or_admin(sender));498499 let mut is_token_owner = || {490 Self::check_token_change_permission(500 *token_owner_result.get_or_insert_with(|| -> Result<bool, DispatchError> {491 collection,501 let is_owned = <PalletStructure<T>>::check_indirectly_owned(492 sender,502 sender.clone(),503 collection.id,493 token_id,504 token_id,494 &property.key,505 None,495 is_token_create,506 nesting_budget,507 )?;508509 Ok(is_owned)496 )?;510 })497511 };512513 for (key, value) in properties {514 let permission = <PalletCommon<T>>::property_permissions(collection.id)515 .get(&key)516 .cloned()517 .unwrap_or_else(PropertyPermission::none);518519 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))520 .get(&key)521 .is_some();522523 match permission {524 PropertyPermission { mutable: false, .. } if is_property_exists => {525 return Err(<CommonError<T>>::NoPermission.into());526 }527528 PropertyPermission {529 collection_admin,530 token_owner,531 ..532 } => {533 //TODO: investigate threats during public minting.534 if is_token_create && (collection_admin || token_owner) && value.is_some() {535 // Pass536 } else if collection_admin && is_collection_admin() {537 // Pass538 } else if token_owner && is_token_owner()? {539 // Pass540 } else {541 fail!(<CommonError<T>>::NoPermission);542 }543 }544 }545546 match value {547 Some(value) => {498 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {548 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {499 let property = property.clone();500 properties.try_set(property.key, property.value)549 properties.try_set(key.clone(), value)501 })550 })551 .map_err(<CommonError<T>>::from)?;552502 .map_err(<CommonError<T>>::from)?;553 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(503554 collection.id,504 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(555 token_id,505 collection.id,556 key,506 token_id,557 ));507 property.key,558 }508 ));559 None => {560 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {561 properties.remove(&key)562 })563 .map_err(<CommonError<T>>::from)?;564565 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(566 collection.id,567 token_id,568 key,569 ));570 }571 }572 }509573510 Ok(())574 Ok(())511 }575 }512576513 #[transactional]514 pub fn set_token_properties(577 pub fn set_token_properties(515 collection: &NonfungibleHandle<T>,578 collection: &NonfungibleHandle<T>,516 sender: &T::CrossAccountId,579 sender: &T::CrossAccountId,517 token_id: TokenId,580 token_id: TokenId,518 properties: Vec<Property>,581 properties: impl Iterator<Item = Property>,519 is_token_create: bool,582 is_token_create: bool,583 nesting_budget: &dyn Budget,520 ) -> DispatchResult {584 ) -> DispatchResult {521 for property in properties {522 Self::set_token_property(collection, sender, token_id, property, is_token_create)?;585 Self::modify_token_properties(523 }586 collection,524587 sender,525 Ok(())588 token_id,589 properties.map(|p| (p.key, Some(p.value))),590 is_token_create,591 nesting_budget,592 )526 }593 }527594528 pub fn delete_token_property(595 pub fn set_token_property(529 collection: &NonfungibleHandle<T>,596 collection: &NonfungibleHandle<T>,530 sender: &T::CrossAccountId,597 sender: &T::CrossAccountId,531 token_id: TokenId,598 token_id: TokenId,532 property_key: PropertyKey,599 property: Property,600 nesting_budget: &dyn Budget,533 ) -> DispatchResult {601 ) -> DispatchResult {602 let is_token_create = false;603534 Self::check_token_change_permission(collection, sender, token_id, &property_key, false)?;604 Self::set_token_properties(535605 collection,536 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {606 sender,537 properties.remove(&property_key)607 token_id,538 })608 [property].into_iter(),539 .map_err(<CommonError<T>>::from)?;609 is_token_create,540610 nesting_budget,541 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(611 )542 collection.id,543 token_id,544 property_key,545 ));546547 Ok(())548 }612 }549613550 fn check_token_change_permission(614 pub fn delete_token_properties(551 collection: &NonfungibleHandle<T>,615 collection: &NonfungibleHandle<T>,552 sender: &T::CrossAccountId,616 sender: &T::CrossAccountId,553 token_id: TokenId,617 token_id: TokenId,554 property_key: &PropertyKey,618 property_keys: impl Iterator<Item = PropertyKey>,555 is_token_create: bool,619 nesting_budget: &dyn Budget,556 ) -> DispatchResult {620 ) -> DispatchResult {557 let permission = <PalletCommon<T>>::property_permissions(collection.id)621 let is_token_create = false;558 .get(property_key)622559 .cloned()560 .unwrap_or_else(PropertyPermission::none);561562 let token_data = <TokenData<T>>::get((collection.id, token_id))563 .ok_or(<CommonError<T>>::TokenNotFound)?;564565 let check_token_owner = || -> DispatchResult {566 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);567 Ok(())568 };569570 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))571 .get(property_key)572 .is_some();573574 match permission {575 PropertyPermission { mutable: false, .. } if is_property_exists => {576 Err(<CommonError<T>>::NoPermission.into())623 Self::modify_token_properties(577 }578579 PropertyPermission {580 collection_admin,624 collection,581 token_owner,625 sender,582 ..626 token_id,583 } => {584 //TODO: investigate threats during public minting.585 if is_token_create && (collection_admin || token_owner) {586 return Ok(());627 property_keys.into_iter().map(|key| (key, None)),587 }628 is_token_create,588629 nesting_budget,589 let mut check_result = Err(<CommonError<T>>::NoPermission.into());630 )590591 if collection_admin {592 check_result = collection.check_is_owner_or_admin(sender);593 }594595 if token_owner {596 check_result.or_else(|_| check_token_owner())597 } else {598 check_result599 }600 }601 }602 }631 }603632604 #[transactional]605 pub fn delete_token_properties(633 pub fn delete_token_property(606 collection: &NonfungibleHandle<T>,634 collection: &NonfungibleHandle<T>,607 sender: &T::CrossAccountId,635 sender: &T::CrossAccountId,608 token_id: TokenId,636 token_id: TokenId,609 property_keys: Vec<PropertyKey>,637 property_key: PropertyKey,638 nesting_budget: &dyn Budget,610 ) -> DispatchResult {639 ) -> DispatchResult {611 for key in property_keys {612 Self::delete_token_property(collection, sender, token_id, key)?;640 Self::delete_token_properties(613 }641 collection,614642 sender,615 Ok(())643 token_id,644 [property_key].into_iter(),645 nesting_budget,646 )616 }647 }617648818 collection,849 collection,819 sender,850 sender,820 TokenId(token),851 TokenId(token),821 data.properties.clone().into_inner(),852 data.properties.clone().into_iter(),822 true,853 true,854 nesting_budget,823 ) {855 ) {824 return TransactionOutcome::Rollback(Err(e));856 return TransactionOutcome::Rollback(Err(e));825 }857 }pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -314,6 +314,7 @@
_sender: T::CrossAccountId,
_token_id: TokenId,
_property: Vec<Property>,
+ _nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
fail!(<Error<T>>::SettingPropertiesNotAllowed)
}
@@ -331,6 +332,7 @@
_sender: T::CrossAccountId,
_token_id: TokenId,
_property_keys: Vec<PropertyKey>,
+ _nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
fail!(<Error<T>>::SettingPropertiesNotAllowed)
}
@@ -340,7 +342,7 @@
_sender: <T>::CrossAccountId,
_from: (CollectionId, TokenId),
_under: TokenId,
- _budget: &dyn Budget,
+ _nesting_budget: &dyn Budget,
) -> sp_runtime::DispatchResult {
fail!(<Error<T>>::RefungibleDisallowsNesting)
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -654,8 +654,9 @@
ensure!(!properties.is_empty(), Error::<T>::EmptyArgument);
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+ let budget = budget::Value::new(NESTING_BUDGET);
- dispatch_tx::<T, _>(collection_id, |d| d.set_token_properties(sender, token_id, properties))
+ dispatch_tx::<T, _>(collection_id, |d| d.set_token_properties(sender, token_id, properties, &budget))
}
#[weight = T::CommonWeightInfo::delete_token_properties(property_keys.len() as u32)]
@@ -669,8 +670,9 @@
ensure!(!property_keys.is_empty(), Error::<T>::EmptyArgument);
let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+ let budget = budget::Value::new(NESTING_BUDGET);
- dispatch_tx::<T, _>(collection_id, |d| d.delete_token_properties(sender, token_id, property_keys))
+ dispatch_tx::<T, _>(collection_id, |d| d.delete_token_properties(sender, token_id, property_keys, &budget))
}
#[weight = T::CommonWeightInfo::set_token_property_permissions(property_permissions.len() as u32)]
tests/src/nesting/properties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/properties.test.ts
+++ b/tests/src/nesting/properties.test.ts
@@ -3,11 +3,13 @@
import {
addCollectionAdminExpectSuccess,
createCollectionExpectSuccess,
+ setCollectionPermissionsExpectSuccess,
createItemExpectSuccess,
getCreateCollectionResult,
transferExpectSuccess,
} from '../util/helpers';
import {IKeyringPair} from '@polkadot/types/types';
+import {tokenIdToAddress} from '../eth/util/helpers';
let alice: IKeyringPair;
let bob: IKeyringPair;
@@ -522,6 +524,7 @@
describe('Integration Test: Token Properties', () => {
let collection: number;
let token: number;
+ let nestedToken: number;
let permissions: {permission: any, signers: IKeyringPair[]}[];
before(async () => {
@@ -544,7 +547,11 @@
beforeEach(async () => {
await usingApi(async () => {
collection = await createCollectionExpectSuccess();
+ await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
+
token = await createItemExpectSuccess(alice, collection, 'NFT');
+ nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, token)});
+
await addCollectionAdminExpectSuccess(alice, collection, bob.address);
await transferExpectSuccess(collection, token, alice, charlie);
});
@@ -681,6 +688,124 @@
expect((await api.query.nonfungible.tokenProperties(collection, token)).toJSON().consumedSpace).to.be.equal(0);
});
});
+
+ it('Assigns properties to a nested token according to permissions', async () => {
+ await usingApi(async api => {
+ const propertyKeys: string[] = [];
+ let i = 0;
+ for (const permission of permissions) {
+ for (const signer of permission.signers) {
+ const key = i + '_' + signer.address;
+ propertyKeys.push(key);
+
+ await expect(executeTransaction(
+ api,
+ alice,
+ api.tx.unique.setTokenPropertyPermissions(collection, [{key: key, permission: permission.permission}]),
+ ), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;
+
+ await expect(executeTransaction(
+ api,
+ signer,
+ api.tx.unique.setTokenProperties(collection, nestedToken, [{key: key, value: 'Serotonin increase'}]),
+ ), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;
+ }
+
+ i++;
+ }
+
+ const properties = (await api.rpc.unique.tokenProperties(collection, nestedToken, propertyKeys)).toHuman() as any[];
+ const tokensData = (await api.rpc.unique.tokenData(collection, nestedToken, propertyKeys)).toHuman().properties as any[];
+ for (let i = 0; i < properties.length; i++) {
+ expect(properties[i].value).to.be.equal('Serotonin increase');
+ expect(tokensData[i].value).to.be.equal('Serotonin increase');
+ }
+ });
+ });
+
+ it('Changes properties of a nested token according to permissions', async () => {
+ await usingApi(async api => {
+ const propertyKeys: string[] = [];
+ let i = 0;
+ for (const permission of permissions) {
+ if (!permission.permission.mutable) continue;
+
+ for (const signer of permission.signers) {
+ const key = i + '_' + signer.address;
+ propertyKeys.push(key);
+
+ await expect(executeTransaction(
+ api,
+ alice,
+ api.tx.unique.setTokenPropertyPermissions(collection, [{key: key, permission: permission.permission}]),
+ ), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;
+
+ await expect(executeTransaction(
+ api,
+ signer,
+ api.tx.unique.setTokenProperties(collection, nestedToken, [{key: key, value: 'Serotonin increase'}]),
+ ), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;
+
+ await expect(executeTransaction(
+ api,
+ signer,
+ api.tx.unique.setTokenProperties(collection, nestedToken, [{key: key, value: 'Serotonin stable'}]),
+ ), `on changing property ${i} by ${signer.address}`).to.not.be.rejected;
+ }
+
+ i++;
+ }
+
+ const properties = (await api.rpc.unique.tokenProperties(collection, nestedToken, propertyKeys)).toHuman() as any[];
+ const tokensData = (await api.rpc.unique.tokenData(collection, nestedToken, propertyKeys)).toHuman().properties as any[];
+ for (let i = 0; i < properties.length; i++) {
+ expect(properties[i].value).to.be.equal('Serotonin stable');
+ expect(tokensData[i].value).to.be.equal('Serotonin stable');
+ }
+ });
+ });
+
+ it('Deletes properties of a nested token according to permissions', async () => {
+ await usingApi(async api => {
+ const propertyKeys: string[] = [];
+ let i = 0;
+
+ for (const permission of permissions) {
+ if (!permission.permission.mutable) continue;
+
+ for (const signer of permission.signers) {
+ const key = i + '_' + signer.address;
+ propertyKeys.push(key);
+
+ await expect(executeTransaction(
+ api,
+ alice,
+ api.tx.unique.setTokenPropertyPermissions(collection, [{key: key, permission: permission.permission}]),
+ ), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;
+
+ await expect(executeTransaction(
+ api,
+ signer,
+ api.tx.unique.setTokenProperties(collection, nestedToken, [{key: key, value: 'Serotonin increase'}]),
+ ), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;
+
+ await expect(executeTransaction(
+ api,
+ signer,
+ api.tx.unique.deleteTokenProperties(collection, nestedToken, [key]),
+ ), `on deleting property ${i} by ${signer.address}`).to.not.be.rejected;
+ }
+
+ i++;
+ }
+
+ const properties = (await api.rpc.unique.tokenProperties(collection, nestedToken, propertyKeys)).toJSON() as any[];
+ expect(properties).to.be.empty;
+ const tokensData = (await api.rpc.unique.tokenData(collection, nestedToken, propertyKeys)).toJSON().properties as any[];
+ expect(tokensData).to.be.empty;
+ expect((await api.query.nonfungible.tokenProperties(collection, nestedToken)).toJSON().consumedSpace).to.be.equal(0);
+ });
+ });
});
describe('Negative Integration Test: Token Properties', () => {
@@ -848,4 +973,4 @@
expect(propertiesMap.consumedSpace).to.be.equal(originalSpace);
});
});
-});
\ No newline at end of file
+});