difftreelog
Add first draft of Properties
in: master
14 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -18,7 +18,7 @@
use core::ops::{Deref, DerefMut};
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
-use sp_std::vec::Vec;
+use sp_std::{vec::Vec, collections::btree_map::BTreeMap};
use pallet_evm::account::CrossAccountId;
use frame_support::{
dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},
@@ -35,7 +35,8 @@
FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT,
CUSTOM_DATA_LIMIT, CollectionLimits, CustomDataLimit, CreateCollectionData, SponsorshipState,
CreateItemExData, SponsoringRateLimit, budget::Budget, COLLECTION_FIELD_LIMIT, CollectionField,
- PhantomType,
+ PhantomType, Property, Properties, PropertiesPermissionMap, PropertyKey, PropertyPermission,
+ PropertiesError,
};
pub use pallet::*;
use sp_core::H160;
@@ -288,6 +289,10 @@
T::CrossAccountId,
u128,
),
+
+ CollectionPropertySet(CollectionId, Property),
+
+ TokenPropertySet(CollectionId, TokenId, Property),
}
#[pallet::error]
@@ -319,7 +324,6 @@
CollectionLimitBoundsExceeded,
/// Tried to enable permissions which are only permitted to be disabled
OwnerPermissionsCantBeReverted,
-
/// Collection settings not allowing items transferring
TransferNotAllowed,
/// Account token limit exceeded per collection
@@ -372,6 +376,25 @@
QueryKind = OptionQuery,
>;
+ /// Collection properties
+ #[pallet::storage]
+ pub type CollectionProperties<T> = StorageMap<
+ Hasher = Blake2_128Concat,
+ Key = CollectionId,
+ Value = Properties,
+ QueryKind = ValueQuery,
+ OnEmpty = up_data_structs::CollectionProperties,
+ >;
+
+ #[pallet::storage]
+ #[pallet::getter(fn property_permission)]
+ pub type CollectionPropertyPermissions<T> = StorageMap<
+ Hasher = Blake2_128Concat,
+ Key = CollectionId,
+ Value = PropertiesPermissionMap,
+ QueryKind = ValueQuery,
+ >;
+
/// Large variable-size collection fields are extracted here
#[pallet::storage]
pub type CollectionData<T> = StorageNMap<
@@ -538,6 +561,7 @@
sponsorship,
limits,
meta_update_permission,
+ ..
} = <CollectionById<T>>::get(collection)?;
Some(RpcCollection {
name: name.into_inner(),
@@ -615,8 +639,25 @@
.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(),
+ // token_property_permissions: data.token_property_permissions.unwrap_or_default(),
+ // properties: Properties::from_collection_props_vec(data.properties)?
};
+ CollectionProperties::<T>::insert(
+ id,
+ Properties::from_collection_props_vec(data.properties)?,
+ );
+
+ let token_props_permissions: PropertiesPermissionMap = data
+ .token_property_permissions
+ .into_iter()
+ .map(|property| (property.key, property.permission))
+ .collect::<BTreeMap<_, _>>()
+ .try_into()
+ .map_err(|_| PropertiesError::PropertyLimitReached)?;
+
+ CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);
+
// Take a (non-refundable) deposit of collection creation
{
let mut imbalance =
@@ -688,6 +729,34 @@
Ok(())
}
+ pub fn change_collection_property(
+ collection: &CollectionHandle<T>,
+ sender: &T::CrossAccountId,
+ property: Property,
+ ) -> DispatchResult {
+ collection.check_is_owner_or_admin(sender)?;
+
+ CollectionProperties::<T>::get(collection.id).try_change_property(property)?;
+
+ Ok(())
+ }
+
+ pub fn change_property_permission(
+ collection: &CollectionHandle<T>,
+ sender: &T::CrossAccountId,
+ property_key: PropertyKey,
+ permission: PropertyPermission,
+ ) -> DispatchResult {
+ collection.check_is_owner_or_admin(sender)?;
+
+ CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {
+ permissions.try_insert(property_key, permission)
+ })
+ .map_err(|_| PropertiesError::PropertyLimitReached)?;
+
+ Ok(())
+ }
+
fn set_field_raw(
collection_id: CollectionId,
field: CollectionField,
@@ -840,6 +909,7 @@
fn create_multiple_items(amount: u32) -> Weight;
fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;
fn burn_item() -> Weight;
+ fn set_property() -> Weight;
fn transfer() -> Weight;
fn approve() -> Weight;
fn transfer_from() -> Weight;
@@ -875,6 +945,19 @@
amount: u128,
) -> DispatchResultWithPostInfo;
+ fn change_collection_property(
+ &self,
+ sender: T::CrossAccountId,
+ property: Property,
+ ) -> DispatchResultWithPostInfo;
+
+ fn change_token_property(
+ &self,
+ sender: T::CrossAccountId,
+ token_id: TokenId,
+ property: Property,
+ ) -> DispatchResultWithPostInfo;
+
fn transfer(
&self,
sender: T::CrossAccountId,
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -21,7 +21,7 @@
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::ArithmeticError;
use sp_std::{vec::Vec, vec};
-use up_data_structs::CustomDataLimit;
+use up_data_structs::{CustomDataLimit, Property};
use crate::{
Allowance, Balance, Config, Error, FungibleHandle, Pallet, SelfWeightOf, weights::WeightInfo,
@@ -50,6 +50,10 @@
<SelfWeightOf<T>>::burn_item()
}
+ fn set_property() -> Weight {
+ <SelfWeightOf<T>>::set_property()
+ }
+
fn transfer() -> Weight {
<SelfWeightOf<T>>::transfer()
}
@@ -225,6 +229,23 @@
)
}
+ fn change_collection_property(
+ &self,
+ _sender: T::CrossAccountId,
+ _property: Property,
+ ) -> DispatchResultWithPostInfo {
+ fail!(<Error<T>>::PropertiesNotAllowed)
+ }
+
+ fn change_token_property(
+ &self,
+ _sender: T::CrossAccountId,
+ _token_id: TokenId,
+ _property: Property,
+ ) -> DispatchResultWithPostInfo {
+ fail!(<Error<T>>::PropertiesNotAllowed)
+ }
+
fn set_variable_metadata(
&self,
_sender: T::CrossAccountId,
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -61,6 +61,8 @@
FungibleItemsDontHaveData,
/// Fungible token does not support nested
FungibleDisallowsNesting,
+ /// Item properties are not allowed
+ PropertiesNotAllowed,
}
#[pallet::config]
pallets/fungible/src/weights.rsdiffbeforeafterboth--- a/pallets/fungible/src/weights.rs
+++ b/pallets/fungible/src/weights.rs
@@ -35,6 +35,7 @@
fn create_item() -> Weight;
fn create_multiple_items_ex(b: u32, ) -> Weight;
fn burn_item() -> Weight;
+ fn set_property() -> Weight;
fn transfer() -> Weight;
fn approve() -> Weight;
fn transfer_from() -> Weight;
@@ -69,6 +70,12 @@
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
+
+ fn set_property() -> Weight {
+ // Error
+ 0
+ }
+
// Storage: Fungible Balance (r:2 w:2)
fn transfer() -> Weight {
(17_713_000 as Weight)
@@ -126,6 +133,12 @@
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
}
+
+ fn set_property() -> Weight {
+ // Error
+ 0
+ }
+
// Storage: Fungible Balance (r:2 w:2)
fn transfer() -> Weight {
(17_713_000 as Weight)
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -17,7 +17,9 @@
use core::marker::PhantomData;
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, BoundedVec};
-use up_data_structs::{TokenId, CustomDataLimit, CreateItemExData, CollectionId, budget::Budget};
+use up_data_structs::{
+ TokenId, CustomDataLimit, CreateItemExData, CollectionId, budget::Budget, Property,
+};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::DispatchError;
use sp_std::vec::Vec;
@@ -48,6 +50,10 @@
<SelfWeightOf<T>>::burn_item()
}
+ fn set_property() -> Weight {
+ <SelfWeightOf<T>>::set_property()
+ }
+
fn transfer() -> Weight {
<SelfWeightOf<T>>::transfer()
}
@@ -235,6 +241,32 @@
}
}
+ fn change_collection_property(
+ &self,
+ sender: T::CrossAccountId,
+ property: Property,
+ ) -> DispatchResultWithPostInfo {
+ // let token_id = None;
+ with_weight(
+ // <Pallet<T>>::change_property(self, &sender, token_id, property),
+ Ok(()),
+ <CommonWeights<T>>::set_property(),
+ )
+ }
+
+ fn change_token_property(
+ &self,
+ sender: T::CrossAccountId,
+ token_id: TokenId,
+ property: Property,
+ ) -> DispatchResultWithPostInfo {
+ with_weight(
+ // <Pallet<T>>::change_property(self, &sender, Some(token_id), property),
+ Ok(()),
+ <CommonWeights<T>>::set_property(),
+ )
+ }
+
fn set_variable_metadata(
&self,
sender: T::CrossAccountId,
pallets/nonfungible/src/lib.rsdiffbeforeafterboth1// 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/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use erc::ERC721Events;20use frame_support::{BoundedVec, ensure, fail};21use up_data_structs::{22 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,23 mapping::TokenAddressMapping, NestingRule, budget::Budget,24};25use pallet_evm::account::CrossAccountId;26use pallet_common::{27 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,28 dispatch::CollectionDispatch,29};30use pallet_structure::Pallet as PalletStructure;31use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};32use sp_core::H160;33use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};34use sp_std::{vec::Vec, vec};35use core::ops::Deref;36use sp_std::collections::btree_map::BTreeMap;37use codec::{Encode, Decode, MaxEncodedLen};38use scale_info::TypeInfo;3940pub use pallet::*;41#[cfg(feature = "runtime-benchmarks")]42pub mod benchmarking;43pub mod common;44pub mod erc;45pub mod weights;4647pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;48pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4950#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]51pub struct ItemData<CrossAccountId> {52 pub const_data: BoundedVec<u8, CustomDataLimit>,53 pub variable_data: BoundedVec<u8, CustomDataLimit>,54 pub owner: CrossAccountId,55}5657#[frame_support::pallet]58pub mod pallet {59 use super::*;60 use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};61 use up_data_structs::{CollectionId, TokenId};62 use super::weights::WeightInfo;6364 #[pallet::error]65 pub enum Error<T> {66 /// Not Nonfungible item data used to mint in Nonfungible collection.67 NotNonfungibleDataUsedToMintFungibleCollectionToken,68 /// Used amount > 1 with NFT69 NonfungibleItemsHaveNoAmount,70 }7172 #[pallet::config]73 pub trait Config:74 frame_system::Config + pallet_common::Config + pallet_structure::Config75 {76 type WeightInfo: WeightInfo;77 }7879 #[pallet::pallet]80 #[pallet::generate_store(pub(super) trait Store)]81 pub struct Pallet<T>(_);8283 #[pallet::storage]84 pub type TokensMinted<T: Config> =85 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;86 #[pallet::storage]87 pub type TokensBurnt<T: Config> =88 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;8990 #[pallet::storage]91 pub type TokenData<T: Config> = StorageNMap<92 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),93 Value = ItemData<T::CrossAccountId>,94 QueryKind = OptionQuery,95 >;9697 /// Used to enumerate tokens owned by account98 #[pallet::storage]99 pub type Owned<T: Config> = StorageNMap<100 Key = (101 Key<Twox64Concat, CollectionId>,102 Key<Blake2_128Concat, T::CrossAccountId>,103 Key<Twox64Concat, TokenId>,104 ),105 Value = bool,106 QueryKind = ValueQuery,107 >;108109 #[pallet::storage]110 pub type AccountBalance<T: Config> = StorageNMap<111 Key = (112 Key<Twox64Concat, CollectionId>,113 Key<Blake2_128Concat, T::CrossAccountId>,114 ),115 Value = u32,116 QueryKind = ValueQuery,117 >;118119 #[pallet::storage]120 pub type Allowance<T: Config> = StorageNMap<121 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),122 Value = T::CrossAccountId,123 QueryKind = OptionQuery,124 >;125}126127pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);128impl<T: Config> NonfungibleHandle<T> {129 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {130 Self(inner)131 }132 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {133 self.0134 }135}136impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {137 fn recorder(&self) -> &SubstrateRecorder<T> {138 self.0.recorder()139 }140 fn into_recorder(self) -> SubstrateRecorder<T> {141 self.0.into_recorder()142 }143}144impl<T: Config> Deref for NonfungibleHandle<T> {145 type Target = pallet_common::CollectionHandle<T>;146147 fn deref(&self) -> &Self::Target {148 &self.0149 }150}151152impl<T: Config> Pallet<T> {153 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {154 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)155 }156 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {157 <TokenData<T>>::contains_key((collection.id, token))158 }159}160161// unchecked calls skips any permission checks162impl<T: Config> Pallet<T> {163 pub fn init_collection(164 owner: T::AccountId,165 data: CreateCollectionData<T::AccountId>,166 ) -> Result<CollectionId, DispatchError> {167 <PalletCommon<T>>::init_collection(owner, data)168 }169 pub fn destroy_collection(170 collection: NonfungibleHandle<T>,171 sender: &T::CrossAccountId,172 ) -> DispatchResult {173 let id = collection.id;174175 // =========176177 PalletCommon::destroy_collection(collection.0, sender)?;178179 <TokenData<T>>::remove_prefix((id,), None);180 <Owned<T>>::remove_prefix((id,), None);181 <TokensMinted<T>>::remove(id);182 <TokensBurnt<T>>::remove(id);183 <Allowance<T>>::remove_prefix((id,), None);184 <AccountBalance<T>>::remove_prefix((id,), None);185 Ok(())186 }187188 pub fn burn(189 collection: &NonfungibleHandle<T>,190 sender: &T::CrossAccountId,191 token: TokenId,192 ) -> DispatchResult {193 let token_data =194 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;195 ensure!(196 &token_data.owner == sender197 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),198 <CommonError<T>>::NoPermission199 );200201 if collection.access == AccessMode::AllowList {202 collection.check_allowlist(sender)?;203 }204205 let burnt = <TokensBurnt<T>>::get(collection.id)206 .checked_add(1)207 .ok_or(ArithmeticError::Overflow)?;208209 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))210 .checked_sub(1)211 .ok_or(ArithmeticError::Overflow)?;212213 if balance == 0 {214 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));215 } else {216 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);217 }218 // =========219220 <Owned<T>>::remove((collection.id, &token_data.owner, token));221 <TokensBurnt<T>>::insert(collection.id, burnt);222 <TokenData<T>>::remove((collection.id, token));223 let old_spender = <Allowance<T>>::take((collection.id, token));224225 if let Some(old_spender) = old_spender {226 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(227 collection.id,228 token,229 sender.clone(),230 old_spender,231 0,232 ));233 }234235 collection.log_mirrored(ERC721Events::Transfer {236 from: *token_data.owner.as_eth(),237 to: H160::default(),238 token_id: token.into(),239 });240 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(241 collection.id,242 token,243 token_data.owner,244 1,245 ));246 Ok(())247 }248249 pub fn transfer(250 collection: &NonfungibleHandle<T>,251 from: &T::CrossAccountId,252 to: &T::CrossAccountId,253 token: TokenId,254 nesting_budget: &dyn Budget,255 ) -> DispatchResult {256 ensure!(257 collection.limits.transfers_enabled(),258 <CommonError<T>>::TransferNotAllowed259 );260261 let token_data =262 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;263 // TODO: require sender to be token, owner, require admins to go through transfer_from264 ensure!(265 &token_data.owner == from266 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),267 <CommonError<T>>::NoPermission268 );269270 if collection.access == AccessMode::AllowList {271 collection.check_allowlist(from)?;272 collection.check_allowlist(to)?;273 }274 <PalletCommon<T>>::ensure_correct_receiver(to)?;275276 let balance_from = <AccountBalance<T>>::get((collection.id, from))277 .checked_sub(1)278 .ok_or(<CommonError<T>>::TokenValueTooLow)?;279 let balance_to = if from != to {280 let balance_to = <AccountBalance<T>>::get((collection.id, to))281 .checked_add(1)282 .ok_or(ArithmeticError::Overflow)?;283284 ensure!(285 balance_to < collection.limits.account_token_ownership_limit(),286 <CommonError<T>>::AccountTokenLimitExceeded,287 );288289 Some(balance_to)290 } else {291 None292 };293294 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(to) {295 let handle = <CollectionHandle<T>>::try_get(target.0)?;296 let dispatch = T::CollectionDispatch::dispatch(handle);297 let dispatch = dispatch.as_dyn();298299 dispatch.check_nesting(300 from.clone(),301 (collection.id, token),302 target.1,303 nesting_budget,304 )?;305 }306307 // =========308309 <TokenData<T>>::insert(310 (collection.id, token),311 ItemData {312 owner: to.clone(),313 ..token_data314 },315 );316317 if let Some(balance_to) = balance_to {318 // from != to319 if balance_from == 0 {320 <AccountBalance<T>>::remove((collection.id, from));321 } else {322 <AccountBalance<T>>::insert((collection.id, from), balance_from);323 }324 <AccountBalance<T>>::insert((collection.id, to), balance_to);325 <Owned<T>>::remove((collection.id, from, token));326 <Owned<T>>::insert((collection.id, to, token), true);327 }328 Self::set_allowance_unchecked(collection, from, token, None, true);329330 collection.log_mirrored(ERC721Events::Transfer {331 from: *from.as_eth(),332 to: *to.as_eth(),333 token_id: token.into(),334 });335 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(336 collection.id,337 token,338 from.clone(),339 to.clone(),340 1,341 ));342 Ok(())343 }344345 pub fn create_multiple_items(346 collection: &NonfungibleHandle<T>,347 sender: &T::CrossAccountId,348 data: Vec<CreateItemData<T>>,349 nesting_budget: &dyn Budget,350 ) -> DispatchResult {351 if !collection.is_owner_or_admin(sender) {352 ensure!(353 collection.mint_mode,354 <CommonError<T>>::PublicMintingNotAllowed355 );356 collection.check_allowlist(sender)?;357358 for item in data.iter() {359 collection.check_allowlist(&item.owner)?;360 }361 }362363 for data in data.iter() {364 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;365 }366367 let first_token = <TokensMinted<T>>::get(collection.id);368 let tokens_minted = first_token369 .checked_add(data.len() as u32)370 .ok_or(ArithmeticError::Overflow)?;371 ensure!(372 tokens_minted <= collection.limits.token_limit(),373 <CommonError<T>>::CollectionTokenLimitExceeded374 );375376 let mut balances = BTreeMap::new();377 for data in &data {378 let balance = balances379 .entry(&data.owner)380 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));381 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;382383 ensure!(384 *balance <= collection.limits.account_token_ownership_limit(),385 <CommonError<T>>::AccountTokenLimitExceeded,386 );387 }388389 for (i, data) in data.iter().enumerate() {390 let token = TokenId(first_token + i as u32 + 1);391 if let Some(target) = T::CrossTokenAddressMapping::address_to_token(&data.owner) {392 let handle = <CollectionHandle<T>>::try_get(target.0)?;393 let dispatch = T::CollectionDispatch::dispatch(handle);394 let dispatch = dispatch.as_dyn();395 dispatch.check_nesting(396 sender.clone(),397 (collection.id, token),398 target.1,399 nesting_budget,400 )?;401 }402 }403404 // =========405406 <TokensMinted<T>>::insert(collection.id, tokens_minted);407 for (account, balance) in balances {408 <AccountBalance<T>>::insert((collection.id, account), balance);409 }410 for (i, data) in data.into_iter().enumerate() {411 let token = first_token + i as u32 + 1;412413 <TokenData<T>>::insert(414 (collection.id, token),415 ItemData {416 const_data: data.const_data,417 variable_data: data.variable_data,418 owner: data.owner.clone(),419 },420 );421 <Owned<T>>::insert((collection.id, &data.owner, token), true);422423 collection.log_mirrored(ERC721Events::Transfer {424 from: H160::default(),425 to: *data.owner.as_eth(),426 token_id: token.into(),427 });428 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(429 collection.id,430 TokenId(token),431 data.owner.clone(),432 1,433 ));434 }435 Ok(())436 }437438 pub fn set_allowance_unchecked(439 collection: &NonfungibleHandle<T>,440 sender: &T::CrossAccountId,441 token: TokenId,442 spender: Option<&T::CrossAccountId>,443 assume_implicit_eth: bool,444 ) {445 if let Some(spender) = spender {446 let old_spender = <Allowance<T>>::get((collection.id, token));447 <Allowance<T>>::insert((collection.id, token), spender);448 // In ERC721 there is only one possible approved user of token, so we set449 // approved user to spender450 collection.log_mirrored(ERC721Events::Approval {451 owner: *sender.as_eth(),452 approved: *spender.as_eth(),453 token_id: token.into(),454 });455 // In Unique chain, any token can have any amount of approved users, so we need to456 // set allowance of old owner to 0, and allowance of new owner to 1457 if old_spender.as_ref() != Some(spender) {458 if let Some(old_owner) = old_spender {459 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(460 collection.id,461 token,462 sender.clone(),463 old_owner,464 0,465 ));466 }467 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(468 collection.id,469 token,470 sender.clone(),471 spender.clone(),472 1,473 ));474 }475 } else {476 let old_spender = <Allowance<T>>::take((collection.id, token));477 if !assume_implicit_eth {478 // In ERC721 there is only one possible approved user of token, so we set479 // approved user to zero address480 collection.log_mirrored(ERC721Events::Approval {481 owner: *sender.as_eth(),482 approved: H160::default(),483 token_id: token.into(),484 });485 }486 // In Unique chain, any token can have any amount of approved users, so we need to487 // set allowance of old owner to 0488 if let Some(old_spender) = old_spender {489 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(490 collection.id,491 token,492 sender.clone(),493 old_spender,494 0,495 ));496 }497 }498 }499500 pub fn set_allowance(501 collection: &NonfungibleHandle<T>,502 sender: &T::CrossAccountId,503 token: TokenId,504 spender: Option<&T::CrossAccountId>,505 ) -> DispatchResult {506 if collection.access == AccessMode::AllowList {507 collection.check_allowlist(sender)?;508 if let Some(spender) = spender {509 collection.check_allowlist(spender)?;510 }511 }512513 if let Some(spender) = spender {514 <PalletCommon<T>>::ensure_correct_receiver(spender)?;515 }516 let token_data =517 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;518 if &token_data.owner != sender {519 ensure!(520 collection.ignores_owned_amount(sender),521 <CommonError<T>>::CantApproveMoreThanOwned522 );523 }524525 // =========526527 Self::set_allowance_unchecked(collection, sender, token, spender, false);528 Ok(())529 }530531 fn check_allowed(532 collection: &NonfungibleHandle<T>,533 spender: &T::CrossAccountId,534 from: &T::CrossAccountId,535 token: TokenId,536 nesting_budget: &dyn Budget,537 ) -> DispatchResult {538 if spender.conv_eq(from) {539 return Ok(());540 }541 if collection.access == AccessMode::AllowList {542 // `from`, `to` checked in [`transfer`]543 collection.check_allowlist(spender)?;544 }545 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {546 // TODO: should collection owner be allowed to perform this transfer?547 ensure!(548 <PalletStructure<T>>::check_indirectly_owned(549 spender.clone(),550 source.0,551 source.1,552 None,553 nesting_budget554 )?,555 <CommonError<T>>::ApprovedValueTooLow,556 );557 return Ok(());558 }559 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {560 return Ok(());561 }562 ensure!(563 collection.ignores_allowance(spender),564 <CommonError<T>>::ApprovedValueTooLow565 );566 Ok(())567 }568569 pub fn transfer_from(570 collection: &NonfungibleHandle<T>,571 spender: &T::CrossAccountId,572 from: &T::CrossAccountId,573 to: &T::CrossAccountId,574 token: TokenId,575 nesting_budget: &dyn Budget,576 ) -> DispatchResult {577 Self::check_allowed(collection, spender, from, token, nesting_budget)?;578579 // =========580581 // Allowance is reset in [`transfer`]582 Self::transfer(collection, from, to, token, nesting_budget)583 }584585 pub fn burn_from(586 collection: &NonfungibleHandle<T>,587 spender: &T::CrossAccountId,588 from: &T::CrossAccountId,589 token: TokenId,590 nesting_budget: &dyn Budget,591 ) -> DispatchResult {592 Self::check_allowed(collection, spender, from, token, nesting_budget)?;593594 // =========595596 Self::burn(collection, from, token)597 }598599 pub fn set_variable_metadata(600 collection: &NonfungibleHandle<T>,601 sender: &T::CrossAccountId,602 token: TokenId,603 data: BoundedVec<u8, CustomDataLimit>,604 ) -> DispatchResult {605 let token_data =606 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;607 collection.check_can_update_meta(sender, &token_data.owner)?;608609 // =========610611 <TokenData<T>>::insert(612 (collection.id, token),613 ItemData {614 variable_data: data,615 ..token_data616 },617 );618 Ok(())619 }620621 pub fn check_nesting(622 handle: &NonfungibleHandle<T>,623 sender: T::CrossAccountId,624 from: (CollectionId, TokenId),625 under: TokenId,626 nesting_budget: &dyn Budget,627 ) -> DispatchResult {628 fn ensure_sender_allowed<T: Config>(629 collection: CollectionId,630 token: TokenId,631 for_nest: (CollectionId, TokenId),632 sender: T::CrossAccountId,633 budget: &dyn Budget,634 ) -> DispatchResult {635 ensure!(636 <PalletStructure<T>>::check_indirectly_owned(637 sender,638 collection,639 token,640 Some(for_nest),641 budget642 )?,643 <CommonError<T>>::OnlyOwnerAllowedToNest,644 );645 Ok(())646 }647 match handle.limits.nesting_rule() {648 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),649 NestingRule::Owner => {650 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?651 }652 NestingRule::OwnerRestricted(whitelist) => {653 ensure!(654 whitelist.contains(&from.0),655 <CommonError<T>>::SourceCollectionIsNotAllowedToNest656 );657 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?658 }659 }660 Ok(())661 }662663 /// Delegated to `create_multiple_items`664 pub fn create_item(665 collection: &NonfungibleHandle<T>,666 sender: &T::CrossAccountId,667 data: CreateItemData<T>,668 nesting_budget: &dyn Budget,669 ) -> DispatchResult {670 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)671 }672}pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -36,6 +36,7 @@
fn create_multiple_items(b: u32, ) -> Weight;
fn create_multiple_items_ex(b: u32, ) -> Weight;
fn burn_item() -> Weight;
+ fn set_property() -> Weight;
fn transfer() -> Weight;
fn approve() -> Weight;
fn transfer_from() -> Weight;
@@ -90,6 +91,12 @@
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
+
+ fn set_property() -> Weight {
+ // TODO calculate appropriate weight
+ 50_000_000 as Weight
+ }
+
// Storage: Nonfungible TokenData (r:1 w:1)
// Storage: Nonfungible AccountBalance (r:2 w:2)
// Storage: Nonfungible Allowance (r:1 w:0)
@@ -179,6 +186,12 @@
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
}
+
+ fn set_property() -> Weight {
+ // TODO calculate appropriate weight
+ 50_000_000 as Weight
+ }
+
// Storage: Nonfungible TokenData (r:1 w:1)
// Storage: Nonfungible AccountBalance (r:2 w:2)
// Storage: Nonfungible Allowance (r:1 w:0)
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -20,7 +20,7 @@
use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight, BoundedVec};
use up_data_structs::{
CollectionId, TokenId, CustomDataLimit, CreateItemExData, CreateRefungibleExData,
- budget::Budget,
+ budget::Budget, Property,
};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::DispatchError;
@@ -66,6 +66,10 @@
max_weight_of!(burn_item_partial(), burn_item_fully())
}
+ fn set_property() -> Weight {
+ <SelfWeightOf<T>>::set_property()
+ }
+
fn transfer() -> Weight {
max_weight_of!(
transfer_normal(),
@@ -244,6 +248,23 @@
)
}
+ fn change_collection_property(
+ &self,
+ _sender: T::CrossAccountId,
+ _property: Property,
+ ) -> DispatchResultWithPostInfo {
+ fail!(<Error<T>>::PropertiesNotAllowed)
+ }
+
+ fn change_token_property(
+ &self,
+ _sender: T::CrossAccountId,
+ _token_id: TokenId,
+ _property: Property,
+ ) -> DispatchResultWithPostInfo {
+ fail!(<Error<T>>::PropertiesNotAllowed)
+ }
+
fn set_variable_metadata(
&self,
sender: T::CrossAccountId,
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -62,6 +62,8 @@
WrongRefungiblePieces,
/// Refungible token can't nest other tokens
RefungibleDisallowsNesting,
+ /// Item properties are not allowed
+ PropertiesNotAllowed,
}
#[pallet::config]
pallets/refungible/src/weights.rsdiffbeforeafterboth--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -38,6 +38,7 @@
fn create_multiple_items_ex_multiple_owners(b: u32, ) -> Weight;
fn burn_item_partial() -> Weight;
fn burn_item_fully() -> Weight;
+ fn set_property() -> Weight;
fn transfer_normal() -> Weight;
fn transfer_creating() -> Weight;
fn transfer_removing() -> Weight;
@@ -129,6 +130,12 @@
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
+
+ fn set_property() -> Weight {
+ // Error
+ 0
+ }
+
// Storage: Refungible Balance (r:2 w:2)
fn transfer_normal() -> Weight {
(19_766_000 as Weight)
@@ -297,6 +304,12 @@
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
}
+
+ fn set_property() -> Weight {
+ // Error
+ 0
+ }
+
// Storage: Refungible Balance (r:2 w:2)
fn transfer_normal() -> Weight {
(19_766_000 as Weight)
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -39,7 +39,7 @@
MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
AccessMode, CreateItemData, CollectionLimits, CollectionId, CollectionMode, TokenId,
SchemaVersion, SponsorshipState, MetaUpdatePermission, CreateCollectionData, CustomDataLimit,
- CreateItemExData, budget, CollectionField,
+ CreateItemExData, budget, CollectionField, Property,
};
use pallet_evm::account::CrossAccountId;
use pallet_common::{
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -22,13 +22,14 @@
};
use frame_support::{
storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},
+ traits::Get,
};
#[cfg(feature = "serde")]
use serde::{Serialize, Deserialize};
use sp_core::U256;
-use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};
+use sp_runtime::{ArithmeticError, sp_std::prelude::Vec, DispatchError};
use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};
use frame_support::{BoundedVec, traits::ConstU32};
use derivative::Derivative;
@@ -85,6 +86,26 @@
pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;
pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;
+pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;
+pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;
+pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;
+
+// pub const MAX_PROPERTY_KEYS_OVERALL_LENGTH: u32 = MAX_PROPERTY_KEY_LENGTH * MAX_PROPERTIES_PER_ITEM;
+pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;
+pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;
+
+pub const MAX_COLLECTION_PROPERTIES_ENCODE_LEN: u32 =
+ MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH + MAX_COLLECTION_PROPERTIES_SIZE;
+
+pub struct MaxPropertiesPermissionsEncodeLen;
+
+impl Get<u32> for MaxPropertiesPermissionsEncodeLen {
+ fn get() -> u32 {
+ MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH
+ + <PropertyPermission as MaxEncodedLen>::max_encoded_len() as u32
+ }
+}
+
/// How much items can be created per single
/// create_many call
pub const MAX_ITEMS_PER_BATCH: u32 = 200;
@@ -310,31 +331,32 @@
OffchainSchema,
}
-#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative, MaxEncodedLen)]
-#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
-#[derivative(Default(bound = ""))]
+#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]
+#[derivative(Debug, Default(bound = ""))]
pub struct CreateCollectionData<AccountId> {
#[derivative(Default(value = "CollectionMode::NFT"))]
pub mode: CollectionMode,
pub access: Option<AccessMode>,
- #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,
- #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,
- #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,
- #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,
pub schema_version: Option<SchemaVersion>,
pub pending_sponsor: Option<AccountId>,
pub limits: Option<CollectionLimits>,
- #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,
- #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
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,
}
+pub type CollectionPropertiesPermissionsVec =
+ BoundedVec<PropertyKeyPermission, MaxPropertiesPermissionsEncodeLen>;
+
+pub type CollectionPropertiesVec =
+ BoundedVec<Property, ConstU32<MAX_COLLECTION_PROPERTIES_ENCODE_LEN>>;
+
#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct NftItemType<AccountId> {
@@ -607,3 +629,128 @@
0
}
}
+
+pub type PropertyKey = BoundedVec<u8, ConstU32<MAX_PROPERTY_KEY_LENGTH>>;
+pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;
+
+#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]
+pub enum PropertyPermission {
+ None,
+ AdminConst,
+ Admin,
+ ItemOwnerConst,
+ ItemOwner,
+ ItemOwnerOrAdmin,
+}
+
+#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]
+pub struct Property {
+ pub key: PropertyKey,
+ pub value: PropertyValue,
+}
+
+#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]
+pub struct PropertyKeyPermission {
+ pub key: PropertyKey,
+ pub permission: PropertyPermission,
+}
+
+pub enum PropertiesError {
+ NoSpaceForProperty,
+ PropertyLimitReached,
+}
+
+impl From<PropertiesError> for DispatchError {
+ fn from(error: PropertiesError) -> Self {
+ match error {
+ PropertiesError::NoSpaceForProperty => DispatchError::Other("no space for property"),
+ PropertiesError::PropertyLimitReached => {
+ DispatchError::Other("property key limit reached")
+ }
+ }
+ }
+}
+
+pub type PropertiesMap =
+ BoundedBTreeMap<PropertyKey, PropertyValue, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
+pub type PropertiesPermissionMap =
+ BoundedBTreeMap<PropertyKey, PropertyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
+
+#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]
+pub struct Properties {
+ map: PropertiesMap,
+ consumed_space: u32,
+ space_limit: u32,
+}
+
+impl Properties {
+ pub fn new(space_limit: u32) -> Self {
+ Self {
+ map: BoundedBTreeMap::new(),
+ consumed_space: 0,
+ space_limit,
+ }
+ }
+
+ pub fn from_collection_props_vec(
+ data: CollectionPropertiesVec,
+ ) -> Result<Self, PropertiesError> {
+ let mut props = Self::new(MAX_COLLECTION_PROPERTIES_SIZE);
+
+ for property in data.into_iter() {
+ props.try_change_property(property)?;
+ }
+
+ Ok(props)
+ }
+
+ pub fn try_change_property(&mut self, property: Property) -> Result<(), PropertiesError> {
+ let value_len = property.value.len();
+
+ if self.consumed_space as usize + value_len > self.space_limit as usize {
+ return Err(PropertiesError::NoSpaceForProperty);
+ }
+
+ self.map
+ .try_insert(property.key, property.value)
+ .map_err(|_| PropertiesError::PropertyLimitReached)?;
+
+ self.consumed_space += value_len as u32;
+
+ Ok(())
+ }
+
+ pub fn get_property(&self, key: &PropertyKey) -> Option<&PropertyValue> {
+ self.map.get(key)
+ }
+}
+
+pub struct CollectionProperties;
+
+impl Get<Properties> for CollectionProperties {
+ fn get() -> Properties {
+ Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)
+ }
+}
+
+pub struct TokenProperties;
+
+impl Get<Properties> for TokenProperties {
+ fn get() -> Properties {
+ Properties::new(MAX_TOKEN_PROPERTIES_SIZE)
+ }
+}
+
+// #[cfg(not(feature = "std"))]
+// fn properties_map_debug(_properties: &PropertiesMap, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
+// write!(f, "<properties>")
+// }
+
+// #[cfg(not(feature = "std"))]
+// fn opt_properties_permissions_map_debug(properties: &Option<PropertiesPermissionMap>, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
+// if properties.is_some() {
+// write!(f, "Some(<properties permissions>)")
+// } else {
+// write!(f, "None")
+// }
+// }
primitives/rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -16,7 +16,9 @@
#![cfg_attr(not(feature = "std"), no_std)]
-use up_data_structs::{CollectionId, TokenId, RpcCollection, CollectionStats, CollectionLimits};
+use up_data_structs::{
+ CollectionId, TokenId, RpcCollection, CollectionStats, CollectionLimits, Property,
+};
use sp_std::vec::Vec;
use codec::Decode;
use sp_runtime::DispatchError;
runtime/common/src/weights.rsdiffbeforeafterboth--- a/runtime/common/src/weights.rs
+++ b/runtime/common/src/weights.rs
@@ -54,6 +54,10 @@
dispatch_weight::<T>() + max_weight_of!(burn_item())
}
+ fn set_property() -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(set_property())
+ }
+
fn transfer() -> Weight {
dispatch_weight::<T>() + max_weight_of!(transfer())
}