difftreelog
Merge branch 'feature/pallet-structure-rebased' of https://github.com/UniqueNetwork/unique-chain into feature/pallet-structure-rebased
in: master
16 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -59,6 +59,7 @@
Properties,
PropertiesPermissionMap,
PropertyKey,
+ PropertyValue,
PropertyPermission,
PropertiesError,
PropertyKeyPermission,
@@ -902,6 +903,12 @@
Ok(())
}
+ pub fn get_collection_property(collection_id: CollectionId, key: &PropertyKey) -> Option<PropertyValue> {
+ Self::collection_properties(collection_id)
+ .get(key)
+ .cloned()
+ }
+
pub fn bytes_keys_to_property_keys(
keys: Vec<Vec<u8>>,
) -> Result<Vec<PropertyKey>, DispatchError> {
@@ -1240,6 +1247,7 @@
fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;
fn const_metadata(&self, token: TokenId) -> Vec<u8>;
+ fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;
fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;
/// Amount of unique collection tokens
fn total_supply(&self) -> u32;
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::{Property, PropertyKey, PropertyKeyPermission};
+use up_data_structs::{Property, PropertyKey, PropertyValue, PropertyKeyPermission};
use crate::{
Allowance, Balance, Config, Error, FungibleHandle, Pallet, SelfWeightOf, weights::WeightInfo,
@@ -319,6 +319,10 @@
Vec::new()
}
+ fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {
+ None
+ }
+
fn token_properties(
&self,
_token_id: TokenId,
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -19,7 +19,7 @@
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight};
use up_data_structs::{
TokenId, CreateItemExData, CollectionId, budget::Budget, Property, PropertyKey,
- PropertyKeyPermission,
+ PropertyKeyPermission, PropertyValue,
};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::DispatchError;
@@ -362,6 +362,12 @@
.into_inner()
}
+ fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {
+ <Pallet<T>>::token_properties((self.id, token_id))
+ .get(key)
+ .cloned()
+ }
+
fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {
let properties = <Pallet<T>>::token_properties((self.id, token_id));
pallets/proxy-rmrk-core/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/pallets/proxy-rmrk-core/Cargo.toml
@@ -0,0 +1,49 @@
+[package]
+name = "pallet-rmrk-core"
+version = "0.1.0"
+license = "GPLv3"
+edition = "2021"
+
+[dependencies.codec]
+default-features = false
+features = ['derive']
+package = 'parity-scale-codec'
+version = '3.1.2'
+
+[dependencies]
+frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
+frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
+sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
+sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
+sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
+pallet-common = { default-features = false, path = '../common' }
+pallet-nonfungible = { default-features = false, path = "../../pallets/nonfungible" }
+# pallet-structure = { default-features = false, path = '../structure' }
+up-data-structs = { default-features = false, path = '../../primitives/data-structs' }
+# evm-coder = { default-features = false, path = '../../crates/evm-coder' }
+# pallet-evm-coder-substrate = { default-features = false, path = '../evm-coder-substrate' }
+pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.21-logs" }
+frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
+scale-info = { version = "2.0.1", default-features = false, features = ["derive"] }
+
+[features]
+default = ["std"]
+std = [
+ "frame-support/std",
+ "frame-system/std",
+ "sp-runtime/std",
+ "sp-std/std",
+ "up-data-structs/std",
+ "pallet-common/std",
+ "pallet-nonfungible/std",
+ "pallet-evm/std",
+ # "pallet-structure/std",
+ # "evm-coder/std",
+ # "pallet-evm-coder-substrate/std",
+ 'frame-benchmarking/std',
+]
+runtime-benchmarks = [
+ 'frame-benchmarking',
+ 'frame-support/runtime-benchmarks',
+ 'frame-system/runtime-benchmarks',
+]
pallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -0,0 +1,256 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+#![cfg_attr(not(feature = "std"), no_std)]
+
+use frame_support::{pallet_prelude::*, transactional, BoundedVec, dispatch::DispatchResult};
+use frame_system::{pallet_prelude::*, ensure_signed};
+use sp_runtime::{DispatchError, traits::StaticLookup};
+use up_data_structs::*;
+use pallet_common::{Pallet as PalletCommon, Error as CommonError, CollectionHandle, CommonCollectionOperations};
+use pallet_nonfungible::{Pallet as PalletNft, NonfungibleHandle};
+use pallet_evm::account::CrossAccountId;
+
+pub use pallet::*;
+
+pub mod misc;
+pub mod property;
+
+use misc::*;
+pub use property::*;
+
+#[frame_support::pallet]
+pub mod pallet {
+ use super::*;
+ use pallet_evm::account;
+
+ #[pallet::config]
+ pub trait Config: frame_system::Config
+ + pallet_common::Config
+ + pallet_nonfungible::Config
+ + account::Config {
+ type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
+ }
+
+ #[pallet::pallet]
+ #[pallet::generate_store(pub(super) trait Store)]
+ pub struct Pallet<T>(_);
+
+ #[pallet::event]
+ #[pallet::generate_deposit(pub(super) fn deposit_event)]
+ pub enum Event<T: Config> {
+ CollectionCreated {
+ issuer: T::AccountId,
+ collection_id: RmrkCollectionId,
+ },
+ CollectionDestroyed {
+ issuer: T::AccountId,
+ collection_id: RmrkCollectionId,
+ },
+ IssuerChanged {
+ old_issuer: T::AccountId,
+ new_issuer: T::AccountId,
+ collection_id: RmrkCollectionId,
+ },
+ CollectionLocked {
+ issuer: T::AccountId,
+ collection_id: RmrkCollectionId,
+ },
+ }
+
+ #[pallet::error]
+ pub enum Error<T> {
+ /* Unique-specific events */
+ CorruptedCollectionType,
+ NotRmrkCollection,
+ RmrkPropertyKeyIsTooLong,
+ RmrkPropertyValueIsTooLong,
+
+ /* RMRK compatible events */
+ CollectionNotEmpty,
+ NoAvailableCollectionId,
+ CollectionUnknown,
+ }
+
+ #[pallet::call]
+ impl<T: Config> Pallet<T> {
+ #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
+ #[transactional]
+ pub fn create_collection(
+ origin: OriginFor<T>,
+ metadata: RmrkString,
+ max: Option<u32>,
+ symbol: RmrkCollectionSymbol,
+ ) -> DispatchResult {
+ let sender = ensure_signed(origin)?;
+
+ let limits = max.map(|max| CollectionLimits {
+ token_limit: Some(max),
+ ..Default::default()
+ });
+
+ let data = CreateCollectionData {
+ limits,
+ token_prefix: symbol.into_inner()
+ .try_into()
+ .map_err(|_| <CommonError<T>>::CollectionTokenPrefixLimitExceeded)?,
+ ..Default::default()
+ };
+
+ let collection_id_res = <PalletNft<T>>::init_collection(sender.clone(), data);
+
+ if let Err(DispatchError::Arithmetic(_)) = &collection_id_res {
+ return Err(<Error<T>>::NoAvailableCollectionId.into());
+ }
+
+ let collection_id = collection_id_res?;
+
+ let collection = Self::get_nft_collection(collection_id)?.into_inner();
+
+ <PalletCommon<T>>::set_scoped_collection_properties(
+ &collection,
+ PropertyScope::Rmrk,
+ [
+ rmrk_property!(Config=T, Metadata: metadata)?,
+ rmrk_property!(Config=T, CollectionType: CollectionType::Regular)?,
+ ].into_iter()
+ )?;
+
+ Self::deposit_event(Event::CollectionCreated {
+ issuer: sender,
+ collection_id: collection_id.0
+ });
+
+ Ok(())
+ }
+
+ #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
+ #[transactional]
+ pub fn destroy_collection(
+ origin: OriginFor<T>,
+ collection_id: RmrkCollectionId,
+ ) -> DispatchResult {
+ let sender = ensure_signed(origin)?;
+ let cross_sender = T::CrossAccountId::from_sub(sender.clone());
+
+ let unique_collection_id = collection_id.into();
+
+ let collection = Self::get_nft_collection(unique_collection_id)?;
+
+ Self::check_collection_type(unique_collection_id, CollectionType::Regular)?;
+
+ ensure!(collection.total_supply() == 0, <Error<T>>::CollectionNotEmpty);
+
+ <PalletNft<T>>::destroy_collection(collection, &cross_sender)?;
+
+ Self::deposit_event(Event::CollectionDestroyed { issuer: sender, collection_id });
+
+ Ok(())
+ }
+
+ #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
+ #[transactional]
+ pub fn change_collection_issuer(
+ origin: OriginFor<T>,
+ collection_id: RmrkCollectionId,
+ new_issuer: <T::Lookup as StaticLookup>::Source,
+ ) -> DispatchResult {
+ let sender = ensure_signed(origin)?;
+
+ let new_issuer = T::Lookup::lookup(new_issuer)?;
+
+ Self::change_collection_owner(
+ collection_id.into(),
+ CollectionType::Regular,
+ sender.clone(),
+ new_issuer.clone()
+ )?;
+
+ Self::deposit_event(Event::IssuerChanged {
+ old_issuer: sender,
+ new_issuer,
+ collection_id,
+ });
+
+ Ok(())
+ }
+
+ #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
+ #[transactional]
+ pub fn lock_collection(
+ origin: OriginFor<T>,
+ collection_id: RmrkCollectionId,
+ ) -> DispatchResult {
+ let sender = ensure_signed(origin)?;
+ let cross_sender = T::CrossAccountId::from_sub(sender.clone());
+
+ let collection = Self::get_nft_collection(collection_id.into())?;
+ collection.check_is_owner(&cross_sender)?;
+
+ let token_count = collection.total_supply();
+
+ let mut collection = collection.into_inner();
+ collection.limits.token_limit = Some(token_count);
+ collection.save()?;
+
+ Self::deposit_event(Event::CollectionLocked { issuer: sender, collection_id });
+
+ Ok(())
+ }
+ }
+}
+
+impl<T: Config> Pallet<T> {
+ fn change_collection_owner(
+ collection_id: CollectionId,
+ collection_type: CollectionType,
+ sender: T::AccountId,
+ new_owner: T::AccountId,
+ ) -> DispatchResult {
+ let mut collection = Self::get_nft_collection(collection_id)?.into_inner();
+ collection.check_is_owner(&T::CrossAccountId::from_sub(sender))?;
+
+ Self::check_collection_type(collection_id, collection_type)?;
+
+ collection.owner = new_owner;
+ collection.save()
+ }
+
+ fn get_nft_collection(collection_id: CollectionId) -> Result<NonfungibleHandle<T>, DispatchError> {
+ let collection = <CollectionHandle<T>>::try_get(collection_id)
+ .map_err(|_| <Error<T>>::CollectionUnknown)?
+ .into_nft_collection()?;
+
+ Ok(collection)
+ }
+
+ fn get_collection_type(collection_id: CollectionId) -> Result<CollectionType, DispatchError> {
+ let collection_type: CollectionType = <PalletCommon<T>>::collection_properties(collection_id)
+ .get(&rmrk_property!(Config=T, CollectionType)?)
+ .ok_or(<Error<T>>::NotRmrkCollection)?
+ .try_into()
+ .map_err(<Error<T>>::from)?;
+
+ Ok(collection_type)
+ }
+
+ fn check_collection_type(collection_id: CollectionId, collection_type: CollectionType) -> DispatchResult {
+ let actual_type = Self::get_collection_type(collection_id)?;
+ ensure!(actual_type == collection_type, <CommonError<T>>::NoPermission);
+
+ Ok(())
+ }
+}
pallets/proxy-rmrk-core/src/misc.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/proxy-rmrk-core/src/misc.rs
@@ -0,0 +1,75 @@
+use super::*;
+use codec::{Encode, Decode};
+use pallet_nonfungible::NonfungibleHandle;
+
+macro_rules! impl_rmrk_value {
+ ($enum_name:path, decode_error: $error:ident) => {
+ impl IntoPropertyValue for $enum_name {
+ fn into_property_value(self) -> Result<PropertyValue, MiscError> {
+ self.encode()
+ .try_into()
+ .map_err(|_| MiscError::RmrkPropertyValueIsTooLong)
+ }
+ }
+
+ impl TryFrom<&PropertyValue> for $enum_name {
+ type Error = MiscError;
+
+ fn try_from(value: &PropertyValue) -> Result<Self, Self::Error> {
+ let mut value = value.as_slice();
+
+ <$enum_name>::decode(&mut value)
+ .map_err(|_| MiscError::$error)
+ }
+ }
+
+ };
+}
+
+pub enum MiscError {
+ RmrkPropertyValueIsTooLong,
+ CorruptedCollectionType,
+}
+
+impl<T: Config> From<MiscError> for Error<T> {
+ fn from(error: MiscError) -> Self {
+ match error {
+ MiscError::RmrkPropertyValueIsTooLong => Self::RmrkPropertyValueIsTooLong,
+ MiscError::CorruptedCollectionType => Self::CorruptedCollectionType,
+ }
+ }
+}
+
+pub trait IntoNftCollection<T: Config> {
+ fn into_nft_collection(self) -> Result<NonfungibleHandle<T>, Error<T>>;
+}
+
+impl<T: Config> IntoNftCollection<T> for CollectionHandle<T> {
+ fn into_nft_collection(self) -> Result<NonfungibleHandle<T>, Error<T>> {
+ match self.mode {
+ CollectionMode::NFT => Ok(NonfungibleHandle::cast(self)),
+ _ => Err(<Error<T>>::NotRmrkCollection)
+ }
+ }
+}
+
+pub trait IntoPropertyValue {
+ fn into_property_value(self) -> Result<PropertyValue, MiscError>;
+}
+
+impl<L: Get<u32>> IntoPropertyValue for BoundedVec<u8, L> {
+ fn into_property_value(self) -> Result<PropertyValue, MiscError> {
+ self.into_inner()
+ .try_into()
+ .map_err(|_| MiscError::RmrkPropertyValueIsTooLong)
+ }
+}
+
+#[derive(Encode, Decode, PartialEq, Eq)]
+pub enum CollectionType {
+ Regular,
+ Resource,
+ Base,
+}
+
+impl_rmrk_value!(CollectionType, decode_error: CorruptedCollectionType);
pallets/proxy-rmrk-core/src/property.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/proxy-rmrk-core/src/property.rs
@@ -0,0 +1,98 @@
+use super::*;
+use core::convert::AsRef;
+
+pub enum RmrkProperty {
+ Metadata,
+ CollectionType,
+ Recipient,
+ Royalty,
+ Equipped,
+ Pending,
+ ResourceCollection,
+ ResourcePriorities,
+ PendingRemoval,
+ Parts,
+ Base,
+ Src,
+ Slot,
+ License,
+ Thumb,
+ EquippedNft,
+ BaseType,
+ // // RmrkPartId(/* Id type? */)
+ EquippableList,
+ ZIndex,
+ ThemeName,
+ ThemeProperty(RmrkString),
+ ThemeInherit,
+}
+
+impl RmrkProperty {
+ pub fn to_key<T: Config>(self) -> Result<PropertyKey, Error<T>> {
+ fn get_bytes<T: AsRef<[u8]>>(container: &T) -> &[u8] {
+ container.as_ref()
+ }
+
+ macro_rules! key {
+ ($($component:expr),+) => {
+ PropertyKey::try_from([$(key!(@ &$component)),+].concat())
+ .map_err(|_| <Error<T>>::RmrkPropertyKeyIsTooLong)
+ };
+
+ (@ $key:expr) => {
+ get_bytes($key)
+ };
+ }
+
+ match self {
+ Self::Metadata => key!("metadata"),
+ Self::CollectionType => key!("collection-type"),
+ Self::Recipient => key!("recipient"),
+ Self::Royalty => key!("royalty"),
+ Self::Equipped => key!("equipped"),
+ Self::Pending => key!("pending"),
+ Self::ResourceCollection => key!("resource-collection"),
+ Self::ResourcePriorities => key!("resource-priorities"),
+ Self::PendingRemoval => key!("pending-removal"),
+ Self::Parts => key!("parts"),
+ Self::Base => key!("base"),
+ Self::Src => key!("src"),
+ Self::Slot => key!("slot"),
+ Self::License => key!("license"),
+ Self::Thumb => key!("thumb"),
+ Self::EquippedNft => key!("equipped-nft"),
+ Self::BaseType => key!("base-type"),
+ // RmrkResourceId(/* Id type? */)
+ // RmrkPartId(/* Id type? */)
+ Self::EquippableList => key!("equippable-list"),
+ Self::ZIndex => key!("z-index"),
+ Self::ThemeName => key!("theme-name"),
+ Self::ThemeProperty(name) => key!("theme-property-", name),
+ Self::ThemeInherit => key!("theme-inherit"),
+ }
+ }
+}
+
+#[macro_export]
+macro_rules! rmrk_property {
+ (Config=$cfg:ty, $key:ident $(($key_ext:expr))?: $value:expr) => {{
+ let key = rmrk_property!(@$cfg, $key $(($key_ext))?)?;
+
+ let value = $value.into_property_value()
+ .map_err(<$crate::Error<$cfg>>::from)?;
+
+ Ok::<_, $crate::Error<$cfg>>(Property {
+ key,
+ value,
+ })
+ }};
+
+ (@$cfg:ty, $key:ident $(($key_ext:expr))?) => {
+ $crate::RmrkProperty::$key $(($key_ext))?.to_key::<$cfg>()
+ };
+
+ (Config=$cfg:ty, $key:ident $(($key_ext:expr))?) => {
+ PropertyScope::Rmrk.apply(rmrk_property!(@$cfg, $key $(($key_ext))?)?)
+ .map_err(|_| <$crate::Error<$cfg>>::RmrkPropertyKeyIsTooLong)
+ };
+}
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};
use up_data_structs::{
CollectionId, TokenId, CreateItemExData, CreateRefungibleExData, budget::Budget, Property,
- PropertyKey, PropertyKeyPermission,
+ PropertyKey, PropertyValue, PropertyKeyPermission,
};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::DispatchError;
@@ -340,6 +340,10 @@
.into_inner()
}
+ fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {
+ None
+ }
+
fn token_properties(
&self,
_token_id: TokenId,
pallets/rmrk-proxy/Cargo.tomldiffbeforeafterboth--- a/pallets/rmrk-proxy/Cargo.toml
+++ /dev/null
@@ -1,49 +0,0 @@
-[package]
-name = "pallet-rmrk-proxy"
-version = "0.1.0"
-license = "GPLv3"
-edition = "2021"
-
-[dependencies.codec]
-default-features = false
-features = ['derive']
-package = 'parity-scale-codec'
-version = '3.1.2'
-
-[dependencies]
-frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
-frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
-sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
-sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
-sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
-pallet-common = { default-features = false, path = '../common' }
-pallet-nonfungible = { default-features = false, path = "../../pallets/nonfungible" }
-# pallet-structure = { default-features = false, path = '../structure' }
-up-data-structs = { default-features = false, path = '../../primitives/data-structs' }
-# evm-coder = { default-features = false, path = '../../crates/evm-coder' }
-# pallet-evm-coder-substrate = { default-features = false, path = '../evm-coder-substrate' }
-pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.21-logs" }
-frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.21" }
-scale-info = { version = "2.0.1", default-features = false, features = ["derive"] }
-
-[features]
-default = ["std"]
-std = [
- "frame-support/std",
- "frame-system/std",
- "sp-runtime/std",
- "sp-std/std",
- "up-data-structs/std",
- "pallet-common/std",
- "pallet-nonfungible/std",
- "pallet-evm/std",
- # "pallet-structure/std",
- # "evm-coder/std",
- # "pallet-evm-coder-substrate/std",
- 'frame-benchmarking/std',
-]
-runtime-benchmarks = [
- 'frame-benchmarking',
- 'frame-support/runtime-benchmarks',
- 'frame-system/runtime-benchmarks',
-]
pallets/rmrk-proxy/src/lib.rsdiffbeforeafterboth--- a/pallets/rmrk-proxy/src/lib.rs
+++ /dev/null
@@ -1,232 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-#![cfg_attr(not(feature = "std"), no_std)]
-
-use frame_support::{pallet_prelude::*, transactional, BoundedVec, traits::ConstU32, dispatch::DispatchResult};
-use frame_system::{pallet_prelude::*, ensure_signed};
-use sp_runtime::DispatchError;
-use up_data_structs::*;
-use pallet_common::{Pallet as PalletCommon, Error as CommonError, CollectionHandle, CommonCollectionOperations};
-use pallet_nonfungible::{Pallet as PalletNft, NonfungibleHandle};
-use pallet_evm::account::CrossAccountId;
-
-pub use pallet::*;
-
-pub mod misc;
-
-use misc::*;
-
-#[frame_support::pallet]
-pub mod pallet {
- use super::*;
- use pallet_evm::account;
-
- #[pallet::config]
- pub trait Config: frame_system::Config
- + pallet_common::Config
- + pallet_nonfungible::Config
- + account::Config {
- type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
- }
-
- #[pallet::pallet]
- #[pallet::generate_store(pub(super) trait Store)]
- pub struct Pallet<T>(_);
-
- #[pallet::event]
- #[pallet::generate_deposit(pub(super) fn deposit_event)]
- pub enum Event<T: Config> {
- CollectionCreated {
- issuer: T::AccountId,
- collection_id: CollectionId,
- },
- CollectionDestroyed {
- issuer: T::AccountId,
- collection_id: CollectionId,
- },
- CollectionLocked {
- issuer: T::AccountId,
- collection_id: CollectionId,
- },
- }
-
- #[pallet::error]
- pub enum Error<T> {
- /* Unique-specific events */
- CorruptedCollectionType,
- NotRmrkCollection,
-
- /* RMRK compatible events */
- CollectionNotEmpty,
- NoAvailableCollectionId,
- CollectionUnknown,
- }
-
- #[pallet::call]
- impl<T: Config> Pallet<T> {
- #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
- #[transactional]
- pub fn create_collection(
- origin: OriginFor<T>,
- metadata: PropertyValue,
- max: Option<u32>,
- symbol: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,
- ) -> DispatchResult {
- let sender = ensure_signed(origin)?;
-
- let limits = max.map(|max| CollectionLimits {
- token_limit: Some(max),
- ..Default::default()
- });
-
- let data = CreateCollectionData {
- limits,
- token_prefix: symbol,
- ..Default::default()
- };
-
- let collection_id_res = <PalletNft<T>>::init_collection(sender.clone(), data);
-
- if let Err(DispatchError::Arithmetic(_)) = &collection_id_res {
- return Err(<Error<T>>::NoAvailableCollectionId.into());
- }
-
- let collection_id = collection_id_res?;
-
- let collection = Self::get_nft_collection(collection_id)?.into_inner();
-
- <PalletCommon<T>>::set_scoped_collection_properties(
- &collection,
- PropertyScope::Rmrk,
- [
- rmrk_property!(Metadata, metadata),
- rmrk_property!(CollectionType, CollectionType::Regular),
- ].into_iter()
- )?;
-
- Self::deposit_event(Event::CollectionCreated { issuer: sender, collection_id });
-
- Ok(())
- }
-
- #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
- #[transactional]
- pub fn destroy_collection(
- origin: OriginFor<T>,
- collection_id: CollectionId,
- ) -> DispatchResult {
- let sender = ensure_signed(origin)?;
- let cross_sender = T::CrossAccountId::from_sub(sender.clone());
-
- let collection = Self::get_nft_collection(collection_id)?;
-
- Self::check_collection_type(collection_id, CollectionType::Regular)?;
-
- ensure!(collection.total_supply() == 0, <Error<T>>::CollectionNotEmpty);
-
- <PalletNft<T>>::destroy_collection(collection, &cross_sender)?;
-
- Self::deposit_event(Event::CollectionDestroyed { issuer: sender, collection_id });
-
- Ok(())
- }
-
- #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
- #[transactional]
- pub fn change_collection_issuer(
- origin: OriginFor<T>,
- collection_id: CollectionId,
- new_issuer: T::AccountId,
- ) -> DispatchResult {
- let sender = ensure_signed(origin)?;
-
- Self::change_collection_owner(
- collection_id,
- CollectionType::Regular,
- sender,
- new_issuer
- )?;
-
- Ok(())
- }
-
- #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
- #[transactional]
- pub fn lock_collection(
- origin: OriginFor<T>,
- collection_id: CollectionId,
- ) -> DispatchResult {
- let sender = ensure_signed(origin)?;
- let cross_sender = T::CrossAccountId::from_sub(sender.clone());
-
- let collection = Self::get_nft_collection(collection_id)?;
- collection.check_is_owner(&cross_sender)?;
-
- let token_count = collection.total_supply();
-
- let mut collection = collection.into_inner();
- collection.limits.token_limit = Some(token_count);
- collection.save()?;
-
- Self::deposit_event(Event::CollectionLocked { issuer: sender, collection_id });
-
- Ok(())
- }
- }
-}
-
-impl<T: Config> Pallet<T> {
- fn change_collection_owner(
- collection_id: CollectionId,
- collection_type: CollectionType,
- sender: T::AccountId,
- new_owner: T::AccountId,
- ) -> DispatchResult {
- let mut collection = Self::get_nft_collection(collection_id)?.into_inner();
- collection.check_is_owner(&T::CrossAccountId::from_sub(sender))?;
-
- Self::check_collection_type(collection_id, collection_type)?;
-
- collection.owner = new_owner;
- collection.save()
- }
-
- fn get_nft_collection(collection_id: CollectionId) -> Result<NonfungibleHandle<T>, DispatchError> {
- let collection = <CollectionHandle<T>>::try_get(collection_id)
- .map_err(|_| <Error<T>>::CollectionUnknown)?
- .into_nft_collection()?;
-
- Ok(collection)
- }
-
- fn get_collection_type(collection_id: CollectionId) -> Result<CollectionType, DispatchError> {
- let collection_type: CollectionType = <PalletCommon<T>>::collection_properties(collection_id)
- .get(&rmrk_property!(CollectionType))
- .ok_or(<Error<T>>::NotRmrkCollection)?
- .try_into()
- .map_err(<Error<T>>::from)?;
-
- Ok(collection_type)
- }
-
- fn check_collection_type(collection_id: CollectionId, collection_type: CollectionType) -> DispatchResult {
- let actual_type = Self::get_collection_type(collection_id)?;
- ensure!(actual_type == collection_type, <CommonError<T>>::NoPermission);
-
- Ok(())
- }
-}
pallets/rmrk-proxy/src/misc.rsdiffbeforeafterboth--- a/pallets/rmrk-proxy/src/misc.rs
+++ /dev/null
@@ -1,98 +0,0 @@
-use super::*;
-use codec::{Encode, Decode};
-use frame_support::dispatch::Vec;
-use pallet_nonfungible::NonfungibleHandle;
-
-#[macro_export]
-macro_rules! rmrk_property {
- ($key:ident, $value:expr) => {
- Property {
- key: rmrk_property!(@raw $key),
- value: $value.into()
- }
- };
-
- (@raw $key:ident) => {
- RmrkProperty::$key.to_key()
- };
-
- ($key:ident) => {
- PropertyScope::Rmrk.apply(rmrk_property!(@raw $key)).unwrap()
- };
-}
-
-macro_rules! impl_rmrk_value {
- ($enum_name:path, decode_error: $error:ident) => {
- impl Into<PropertyValue> for $enum_name {
- fn into(self) -> PropertyValue {
- self.encode().try_into().unwrap()
- }
- }
-
- impl TryFrom<&PropertyValue> for $enum_name {
- type Error = MiscError;
-
- fn try_from(value: &PropertyValue) -> Result<Self, Self::Error> {
- let mut value = value.as_slice();
-
- <$enum_name>::decode(&mut value)
- .map_err(|_| MiscError::$error)
- }
- }
-
- };
-}
-
-pub enum MiscError {
- CorruptedCollectionType,
-}
-
-impl<T: Config> From<MiscError> for Error<T> {
- fn from(error: MiscError) -> Self {
- match error {
- MiscError::CorruptedCollectionType => Self::CorruptedCollectionType,
- }
- }
-}
-
-pub trait IntoNftCollection<T: Config> {
- fn into_nft_collection(self) -> Result<NonfungibleHandle<T>, Error<T>>;
-}
-
-impl<T: Config> IntoNftCollection<T> for CollectionHandle<T> {
- fn into_nft_collection(self) -> Result<NonfungibleHandle<T>, Error<T>> {
- match self.mode {
- CollectionMode::NFT => Ok(NonfungibleHandle::cast(self)),
- _ => Err(<Error<T>>::NotRmrkCollection)
- }
- }
-}
-
-pub enum RmrkProperty {
- Metadata,
- CollectionType,
-}
-
-impl RmrkProperty {
- pub fn to_key(self) -> PropertyKey {
- let key = |str_key: &str| {
- PropertyKey::try_from(
- str_key.bytes().collect::<Vec<_>>()
- ).unwrap()
- };
-
- match self {
- Self::Metadata => key("metadata"),
- Self::CollectionType => key("collection-type"),
- }
- }
-}
-
-#[derive(Encode, Decode, PartialEq, Eq)]
-pub enum CollectionType {
- Regular,
- Resource,
- Base,
-}
-
-impl_rmrk_value!(CollectionType, decode_error: CorruptedCollectionType);
primitives/data-structs/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 core::{20 convert::{TryFrom, TryInto},21 fmt,22};23use frame_support::{24 storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},25 traits::Get,26 parameter_types,27};2829#[cfg(feature = "serde")]30use serde::{Serialize, Deserialize};3132use sp_core::U256;33use sp_runtime::{ArithmeticError, sp_std::prelude::Vec, Permill};34use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};35use frame_support::{BoundedVec, traits::ConstU32};36use derivative::Derivative;37use scale_info::TypeInfo;3839// RMRK40use rmrk_types::{41 CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme, ThemeProperty,42};43pub use rmrk_types::{44 primitives::{45 CollectionId as RmrkCollectionId, NftId as RmrkNftId, BaseId as RmrkBaseId,46 PartId as RmrkPartId, ResourceId as RmrkResourceId,47 },48 NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,49};5051mod bounded;52pub mod budget;53pub mod mapping;54mod migration;5556pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;57pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;58pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;5960pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {61 100_00062} else {63 1064};65pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {66 100_00067} else {68 1069};70pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {71 204872} else {73 1074};75pub const COLLECTION_ADMINS_LIMIT: u32 = 5;76pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;77pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {78 1_000_00079} else {80 1081};8283// Timeouts for item types in passed blocks84pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;85pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;86pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;8788pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;8990// Schema limits91pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;92pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;93pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;9495pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;9697pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;98pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;99pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;100101pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;102pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;103pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;104105// pub const MAX_PROPERTY_KEYS_OVERALL_LENGTH: u32 = MAX_PROPERTY_KEY_LENGTH * MAX_PROPERTIES_PER_ITEM;106pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;107pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;108109pub const MAX_COLLECTION_PROPERTIES_ENCODE_LEN: u32 =110 MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH + MAX_COLLECTION_PROPERTIES_SIZE;111112// RMRK constants113pub const RMRK_STRING_LIMIT: u32 = 128;114pub const RMRK_COLLECTION_SYMBOL_LIMIT: u32 = 100;115pub const RMRK_RESOURCE_SYMBOL_LIMIT: u32 = 10;116pub const RMRK_KEY_LIMIT: u32 = 32;117pub const RMRK_VALUE_LIMIT: u32 = 256;118119pub struct MaxPropertiesPermissionsEncodeLen;120121impl Get<u32> for MaxPropertiesPermissionsEncodeLen {122 fn get() -> u32 {123 MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH124 + <PropertyPermission as MaxEncodedLen>::max_encoded_len() as u32125 }126}127128/// How much items can be created per single129/// create_many call130pub const MAX_ITEMS_PER_BATCH: u32 = 200;131132pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;133134#[derive(135 Encode,136 Decode,137 PartialEq,138 Eq,139 PartialOrd,140 Ord,141 Clone,142 Copy,143 Debug,144 Default,145 TypeInfo,146 MaxEncodedLen,147)]148#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]149pub struct CollectionId(pub u32);150impl EncodeLike<u32> for CollectionId {}151impl EncodeLike<CollectionId> for u32 {}152153#[derive(154 Encode,155 Decode,156 PartialEq,157 Eq,158 PartialOrd,159 Ord,160 Clone,161 Copy,162 Debug,163 Default,164 TypeInfo,165 MaxEncodedLen,166)]167#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]168pub struct TokenId(pub u32);169impl EncodeLike<u32> for TokenId {}170impl EncodeLike<TokenId> for u32 {}171172impl TokenId {173 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {174 self.0175 .checked_add(1)176 .ok_or(ArithmeticError::Overflow)177 .map(Self)178 }179}180181impl From<TokenId> for U256 {182 fn from(t: TokenId) -> Self {183 t.0.into()184 }185}186187impl TryFrom<U256> for TokenId {188 type Error = &'static str;189190 fn try_from(value: U256) -> Result<Self, Self::Error> {191 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))192 }193}194195#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]196#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]197pub struct TokenData<CrossAccountId> {198 pub const_data: Vec<u8>,199 pub properties: Vec<Property>,200 pub owner: Option<CrossAccountId>,201}202203pub struct OverflowError;204impl From<OverflowError> for &'static str {205 fn from(_: OverflowError) -> Self {206 "overflow occured"207 }208}209210pub type DecimalPoints = u8;211212#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]213#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]214pub enum CollectionMode {215 NFT,216 // decimal points217 Fungible(DecimalPoints),218 ReFungible,219}220221impl CollectionMode {222 pub fn id(&self) -> u8 {223 match self {224 CollectionMode::NFT => 1,225 CollectionMode::Fungible(_) => 2,226 CollectionMode::ReFungible => 3,227 }228 }229}230231pub trait SponsoringResolve<AccountId, Call> {232 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;233}234235#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]236#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]237pub enum AccessMode {238 Normal,239 AllowList,240}241impl Default for AccessMode {242 fn default() -> Self {243 Self::Normal244 }245}246247#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]248#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]249pub enum SchemaVersion {250 ImageURL,251 Unique,252}253impl Default for SchemaVersion {254 fn default() -> Self {255 Self::ImageURL256 }257}258259#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]260#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]261pub struct Ownership<AccountId> {262 pub owner: AccountId,263 pub fraction: u128,264}265266#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]267#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]268pub enum SponsorshipState<AccountId> {269 /// The fees are applied to the transaction sender270 Disabled,271 Unconfirmed(AccountId),272 /// Transactions are sponsored by specified account273 Confirmed(AccountId),274}275276impl<AccountId> SponsorshipState<AccountId> {277 pub fn sponsor(&self) -> Option<&AccountId> {278 match self {279 Self::Confirmed(sponsor) => Some(sponsor),280 _ => None,281 }282 }283284 pub fn pending_sponsor(&self) -> Option<&AccountId> {285 match self {286 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),287 _ => None,288 }289 }290291 pub fn confirmed(&self) -> bool {292 matches!(self, Self::Confirmed(_))293 }294}295296impl<T> Default for SponsorshipState<T> {297 fn default() -> Self {298 Self::Disabled299 }300}301302/// Used in storage303#[struct_versioning::versioned(version = 2, upper)]304#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]305pub struct Collection<AccountId> {306 pub owner: AccountId,307 pub mode: CollectionMode,308 pub access: AccessMode,309 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,310 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,311 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,312 pub mint_mode: bool,313314 #[version(..2)]315 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,316317 pub schema_version: SchemaVersion,318 pub sponsorship: SponsorshipState<AccountId>,319320 #[version(..2)]321 pub limits: CollectionLimitsVersion1, // Collection private restrictions322 #[version(2.., upper(limits.into()))]323 pub limits: CollectionLimitsVersion2,324325 #[version(..2)]326 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,327328 #[version(..2)]329 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,330331 #[version(..2)]332 pub meta_update_permission: MetaUpdatePermission,333}334335/// Used in RPC calls336#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]337#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]338pub struct RpcCollection<AccountId> {339 pub owner: AccountId,340 pub mode: CollectionMode,341 pub access: AccessMode,342 pub name: Vec<u16>,343 pub description: Vec<u16>,344 pub token_prefix: Vec<u8>,345 pub mint_mode: bool,346 pub offchain_schema: Vec<u8>,347 pub schema_version: SchemaVersion,348 pub sponsorship: SponsorshipState<AccountId>,349 pub limits: CollectionLimits,350 pub const_on_chain_schema: Vec<u8>,351 pub token_property_permissions: Vec<PropertyKeyPermission>,352 pub properties: Vec<Property>,353}354355#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]356#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]357pub enum CollectionField {358 ConstOnChainSchema,359 OffchainSchema,360}361362#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]363#[derivative(Debug, Default(bound = ""))]364pub struct CreateCollectionData<AccountId> {365 #[derivative(Default(value = "CollectionMode::NFT"))]366 pub mode: CollectionMode,367 pub access: Option<AccessMode>,368 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,369 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,370 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,371 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,372 pub schema_version: Option<SchemaVersion>,373 pub pending_sponsor: Option<AccountId>,374 pub limits: Option<CollectionLimits>,375 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,376 pub token_property_permissions: CollectionPropertiesPermissionsVec,377 pub properties: CollectionPropertiesVec,378}379380pub type CollectionPropertiesPermissionsVec =381 BoundedVec<PropertyKeyPermission, MaxPropertiesPermissionsEncodeLen>;382383pub type CollectionPropertiesVec =384 BoundedVec<Property, ConstU32<MAX_COLLECTION_PROPERTIES_ENCODE_LEN>>;385386/// All fields are wrapped in `Option`s, where None means chain default387#[struct_versioning::versioned(version = 2, upper)]388#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]389#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]390pub struct CollectionLimits {391 pub account_token_ownership_limit: Option<u32>,392 pub sponsored_data_size: Option<u32>,393394 /// FIXME should we delete this or repurpose it?395 /// None - setVariableMetadata is not sponsored396 /// Some(v) - setVariableMetadata is sponsored397 /// if there is v block between txs398 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,399 pub token_limit: Option<u32>,400401 // Timeouts for item types in passed blocks402 pub sponsor_transfer_timeout: Option<u32>,403 pub sponsor_approve_timeout: Option<u32>,404 pub owner_can_transfer: Option<bool>,405 pub owner_can_destroy: Option<bool>,406 pub transfers_enabled: Option<bool>,407408 #[version(2.., upper(None))]409 pub nesting_rule: Option<NestingRule>,410}411412impl CollectionLimits {413 pub fn account_token_ownership_limit(&self) -> u32 {414 self.account_token_ownership_limit415 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)416 .min(MAX_TOKEN_OWNERSHIP)417 }418 pub fn sponsored_data_size(&self) -> u32 {419 self.sponsored_data_size420 .unwrap_or(CUSTOM_DATA_LIMIT)421 .min(CUSTOM_DATA_LIMIT)422 }423 pub fn token_limit(&self) -> u32 {424 self.token_limit425 .unwrap_or(COLLECTION_TOKEN_LIMIT)426 .min(COLLECTION_TOKEN_LIMIT)427 }428 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {429 self.sponsor_transfer_timeout430 .unwrap_or(default)431 .min(MAX_SPONSOR_TIMEOUT)432 }433 pub fn sponsor_approve_timeout(&self) -> u32 {434 self.sponsor_approve_timeout435 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)436 .min(MAX_SPONSOR_TIMEOUT)437 }438 pub fn owner_can_transfer(&self) -> bool {439 self.owner_can_transfer.unwrap_or(true)440 }441 pub fn owner_can_destroy(&self) -> bool {442 self.owner_can_destroy.unwrap_or(true)443 }444 pub fn transfers_enabled(&self) -> bool {445 self.transfers_enabled.unwrap_or(true)446 }447 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {448 match self449 .sponsored_data_rate_limit450 .unwrap_or(SponsoringRateLimit::SponsoringDisabled)451 {452 SponsoringRateLimit::SponsoringDisabled => None,453 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),454 }455 }456 pub fn nesting_rule(&self) -> &NestingRule {457 static DEFAULT: NestingRule = NestingRule::Disabled;458 self.nesting_rule.as_ref().unwrap_or(&DEFAULT)459 }460}461462#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]463#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]464#[derivative(Debug)]465pub enum NestingRule {466 /// No one can nest tokens467 Disabled,468 /// Owner can nest any tokens469 Owner,470 /// Owner can nest tokens from specified collections471 OwnerRestricted(472 #[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]473 #[derivative(Debug(format_with = "bounded::set_debug"))]474 BoundedBTreeSet<CollectionId, ConstU32<16>>,475 ),476}477478#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]479#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]480pub enum SponsoringRateLimit {481 SponsoringDisabled,482 Blocks(u32),483}484485#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]486#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]487#[derivative(Debug)]488pub struct CreateNftData {489 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]490 #[derivative(Debug(format_with = "bounded::vec_debug"))]491 pub const_data: BoundedVec<u8, CustomDataLimit>,492493 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]494 #[derivative(Debug(format_with = "bounded::vec_debug"))]495 pub properties: CollectionPropertiesVec,496}497498#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]499#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]500pub struct CreateFungibleData {501 pub value: u128,502}503504#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]505#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]506#[derivative(Debug)]507pub struct CreateReFungibleData {508 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]509 #[derivative(Debug(format_with = "bounded::vec_debug"))]510 pub const_data: BoundedVec<u8, CustomDataLimit>,511 pub pieces: u128,512}513514#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]515pub enum MetaUpdatePermission {516 ItemOwner,517 Admin,518 None,519}520521#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]522#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]523pub enum CreateItemData {524 NFT(CreateNftData),525 Fungible(CreateFungibleData),526 ReFungible(CreateReFungibleData),527}528529#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]530#[derivative(Debug)]531pub struct CreateNftExData<CrossAccountId> {532 #[derivative(Debug(format_with = "bounded::vec_debug"))]533 pub const_data: BoundedVec<u8, CustomDataLimit>,534 #[derivative(Debug(format_with = "bounded::vec_debug"))]535 pub properties: CollectionPropertiesVec,536 pub owner: CrossAccountId,537}538539#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]540#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]541pub struct CreateRefungibleExData<CrossAccountId> {542 #[derivative(Debug(format_with = "bounded::vec_debug"))]543 pub const_data: BoundedVec<u8, CustomDataLimit>,544 #[derivative(Debug(format_with = "bounded::map_debug"))]545 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,546}547548#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]549#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]550pub enum CreateItemExData<CrossAccountId> {551 NFT(552 #[derivative(Debug(format_with = "bounded::vec_debug"))]553 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,554 ),555 Fungible(556 #[derivative(Debug(format_with = "bounded::map_debug"))]557 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,558 ),559 /// Many tokens, each may have only one owner560 RefungibleMultipleItems(561 #[derivative(Debug(format_with = "bounded::vec_debug"))]562 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,563 ),564 /// Single token, which may have many owners565 RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),566}567568impl CreateItemData {569 pub fn data_size(&self) -> usize {570 match self {571 CreateItemData::NFT(data) => data.const_data.len(),572 CreateItemData::ReFungible(data) => data.const_data.len(),573 _ => 0,574 }575 }576}577578impl From<CreateNftData> for CreateItemData {579 fn from(item: CreateNftData) -> Self {580 CreateItemData::NFT(item)581 }582}583584impl From<CreateReFungibleData> for CreateItemData {585 fn from(item: CreateReFungibleData) -> Self {586 CreateItemData::ReFungible(item)587 }588}589590impl From<CreateFungibleData> for CreateItemData {591 fn from(item: CreateFungibleData) -> Self {592 CreateItemData::Fungible(item)593 }594}595596#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]597#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]598pub struct CollectionStats {599 pub created: u32,600 pub destroyed: u32,601 pub alive: u32,602}603604#[derive(Encode, Decode, Clone, Debug)]605#[cfg_attr(feature = "std", derive(PartialEq))]606pub struct PhantomType<T>(core::marker::PhantomData<T>);607608impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {609 type Identity = PhantomType<T>;610611 fn type_info() -> scale_info::Type {612 use scale_info::{613 Type, Path,614 build::{FieldsBuilder, UnnamedFields},615 type_params,616 };617 Type::builder()618 .path(Path::new("up_data_structs", "PhantomType"))619 .type_params(type_params!(T))620 .composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))621 }622}623impl<T> MaxEncodedLen for PhantomType<T> {624 fn max_encoded_len() -> usize {625 0626 }627}628629pub type PropertyKey = BoundedVec<u8, ConstU32<MAX_PROPERTY_KEY_LENGTH>>;630pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;631632#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]633#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]634pub struct PropertyPermission {635 pub mutable: bool,636 pub collection_admin: bool,637 pub token_owner: bool,638}639640impl PropertyPermission {641 pub fn none() -> Self {642 Self {643 mutable: true,644 collection_admin: false,645 token_owner: false,646 }647 }648}649650#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]651#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]652pub struct Property {653 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]654 pub key: PropertyKey,655656 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]657 pub value: PropertyValue,658}659660impl Into<(PropertyKey, PropertyValue)> for Property {661 fn into(self) -> (PropertyKey, PropertyValue) {662 (self.key, self.value)663 }664}665666#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]667#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]668pub struct PropertyKeyPermission {669 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]670 pub key: PropertyKey,671672 pub permission: PropertyPermission,673}674675impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {676 fn into(self) -> (PropertyKey, PropertyPermission) {677 (self.key, self.permission)678 }679}680681#[derive(Debug)]682pub enum PropertiesError {683 NoSpaceForProperty,684 PropertyLimitReached,685 InvalidCharacterInPropertyKey,686 PropertyKeyIsTooLong,687 EmptyPropertyKey,688}689690#[derive(Clone, Copy)]691pub enum PropertyScope {692 None,693 Rmrk,694}695696impl PropertyScope {697 pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {698 let scope_str: &[u8] = match self {699 Self::None => return Ok(key),700 Self::Rmrk => b"rmrk",701 };702703 [scope_str, b":", key.as_slice()]704 .concat()705 .try_into()706 .map_err(|_| PropertiesError::PropertyKeyIsTooLong)707 }708}709710pub trait TrySetProperty: Sized {711 type Value;712713 fn try_scoped_set(714 &mut self,715 scope: PropertyScope,716 key: PropertyKey,717 value: Self::Value,718 ) -> Result<(), PropertiesError>;719720 fn try_scoped_set_from_iter<I, KV>(721 &mut self,722 scope: PropertyScope,723 iter: I,724 ) -> Result<(), PropertiesError>725 where726 I: Iterator<Item=KV>,727 KV: Into<(PropertyKey, Self::Value)>728 {729 for kv in iter {730 let (key, value) = kv.into();731 self.try_scoped_set(scope, key, value)?;732 }733734 Ok(())735 }736737 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {738 self.try_scoped_set(PropertyScope::None, key, value)739 }740741 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>742 where743 I: Iterator<Item=KV>,744 KV: Into<(PropertyKey, Self::Value)>745 {746 self.try_scoped_set_from_iter(PropertyScope::None, iter)747 }748}749750#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]751#[derivative(Default(bound = ""))]752pub struct PropertiesMap<Value>(753 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,754);755756impl<Value> PropertiesMap<Value> {757 pub fn new() -> Self {758 Self(BoundedBTreeMap::new())759 }760761 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {762 Self::check_property_key(key)?;763764 Ok(self.0.remove(key))765 }766767 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {768 self.0.get(key)769 }770771 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &Value)> {772 self.0.iter()773 }774775 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {776 if key.is_empty() {777 return Err(PropertiesError::EmptyPropertyKey);778 }779780 for byte in key.as_slice().iter() {781 let byte = *byte;782783 if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' {784 return Err(PropertiesError::InvalidCharacterInPropertyKey);785 }786 }787788 Ok(())789 }790}791792impl<Value> TrySetProperty for PropertiesMap<Value> {793 type Value = Value;794795 fn try_scoped_set(796 &mut self,797 scope: PropertyScope,798 key: PropertyKey,799 value: Self::Value,800 ) -> Result<(), PropertiesError> {801 Self::check_property_key(&key)?;802803 let key = scope.apply(key)?;804 self.0805 .try_insert(key, value)806 .map_err(|_| PropertiesError::PropertyLimitReached)?;807808 Ok(())809 }810}811812pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;813814#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]815pub struct Properties {816 map: PropertiesMap<PropertyValue>,817 consumed_space: u32,818 space_limit: u32,819}820821impl Properties {822 pub fn new(space_limit: u32) -> Self {823 Self {824 map: PropertiesMap::new(),825 consumed_space: 0,826 space_limit,827 }828 }829830 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {831 let value = self.map.remove(key)?;832833 if let Some(ref value) = value {834 let value_len = value.len() as u32;835 self.consumed_space -= value_len;836 }837838 Ok(value)839 }840841 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {842 self.map.get(key)843 }844845 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {846 self.map.iter()847 }848}849850impl TrySetProperty for Properties {851 type Value = PropertyValue;852853 fn try_scoped_set(854 &mut self,855 scope: PropertyScope,856 key: PropertyKey,857 value: Self::Value,858 ) -> Result<(), PropertiesError> {859 let value_len = value.len();860861 if self.consumed_space as usize + value_len > self.space_limit as usize {862 return Err(PropertiesError::NoSpaceForProperty);863 }864865 self.map.try_scoped_set(scope, key, value)?;866867 self.consumed_space += value_len as u32;868869 Ok(())870 }871}872873pub struct CollectionProperties;874875impl Get<Properties> for CollectionProperties {876 fn get() -> Properties {877 Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)878 }879}880881pub struct TokenProperties;882883impl Get<Properties> for TokenProperties {884 fn get() -> Properties {885 Properties::new(MAX_TOKEN_PROPERTIES_SIZE)886 }887}888889// RMRK890// todo document?891parameter_types! {892 #[derive(PartialEq, TypeInfo)]893 pub const RmrkStringLimit: u32 = 128;894 #[derive(PartialEq)]895 pub const RmrkCollectionSymbolLimit: u32 = 100;896 #[derive(PartialEq)]897 pub const RmrkResourceSymbolLimit: u32 = 10;898 #[derive(PartialEq)]899 pub const RmrkKeyLimit: u32 = 32;900 #[derive(PartialEq)]901 pub const RmrkValueLimit: u32 = 256;902 #[derive(PartialEq)]903 pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;904 #[derive(PartialEq)]905 pub const RmrkPartsLimit: u32 = 3;906}907908pub type RmrkCollectionInfo<AccountId> =909 CollectionInfo<RmrkString, BoundedVec<u8, RmrkCollectionSymbolLimit>, AccountId>;910pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;911pub type RmrkResourceInfo = ResourceInfo<912 BoundedVec<u8, RmrkResourceSymbolLimit>,913 RmrkString,914 BoundedVec<RmrkPartId, RmrkPartsLimit>,915>;916pub type RmrkPropertyInfo =917 PropertyInfo<BoundedVec<u8, RmrkKeyLimit>, BoundedVec<u8, RmrkValueLimit>>;918pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;919pub type RmrkPartType =920 PartType<RmrkString, BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>>;921pub type RmrkTheme = Theme<RmrkString, Vec<ThemeProperty<RmrkString>>>;922923pub type RmrkRpcString = Vec<u8>;924pub type RmrkThemeName = RmrkRpcString;925pub type RmrkPropertyKey = RmrkRpcString;926927type RmrkString = BoundedVec<u8, RmrkStringLimit>;1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use core::{20 convert::{TryFrom, TryInto},21 fmt,22};23use frame_support::{24 storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},25 traits::Get,26 parameter_types,27};2829#[cfg(feature = "serde")]30use serde::{Serialize, Deserialize};3132use sp_core::U256;33use sp_runtime::{ArithmeticError, sp_std::prelude::Vec, Permill};34use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};35use frame_support::{BoundedVec, traits::ConstU32};36use derivative::Derivative;37use scale_info::TypeInfo;3839// RMRK40use rmrk_types::{41 CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme, ThemeProperty,42};43pub use rmrk_types::{44 primitives::{45 CollectionId as RmrkCollectionId, NftId as RmrkNftId, BaseId as RmrkBaseId,46 PartId as RmrkPartId, ResourceId as RmrkResourceId,47 },48 NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,49};5051mod bounded;52pub mod budget;53pub mod mapping;54mod migration;5556pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;57pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;58pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;5960pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {61 100_00062} else {63 1064};65pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {66 100_00067} else {68 1069};70pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {71 204872} else {73 1074};75pub const COLLECTION_ADMINS_LIMIT: u32 = 5;76pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;77pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {78 1_000_00079} else {80 1081};8283// Timeouts for item types in passed blocks84pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;85pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;86pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;8788pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;8990// Schema limits91pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;92pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;93pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;9495pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;9697pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;98pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;99pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;100101pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;102pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;103pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;104105// pub const MAX_PROPERTY_KEYS_OVERALL_LENGTH: u32 = MAX_PROPERTY_KEY_LENGTH * MAX_PROPERTIES_PER_ITEM;106pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;107pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;108109pub const MAX_COLLECTION_PROPERTIES_ENCODE_LEN: u32 =110 MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH + MAX_COLLECTION_PROPERTIES_SIZE;111112// RMRK constants113pub const RMRK_STRING_LIMIT: u32 = 128;114pub const RMRK_COLLECTION_SYMBOL_LIMIT: u32 = 100;115pub const RMRK_RESOURCE_SYMBOL_LIMIT: u32 = 10;116pub const RMRK_KEY_LIMIT: u32 = 32;117pub const RMRK_VALUE_LIMIT: u32 = 256;118119pub struct MaxPropertiesPermissionsEncodeLen;120121impl Get<u32> for MaxPropertiesPermissionsEncodeLen {122 fn get() -> u32 {123 MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH124 + <PropertyPermission as MaxEncodedLen>::max_encoded_len() as u32125 }126}127128/// How much items can be created per single129/// create_many call130pub const MAX_ITEMS_PER_BATCH: u32 = 200;131132pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;133134#[derive(135 Encode,136 Decode,137 PartialEq,138 Eq,139 PartialOrd,140 Ord,141 Clone,142 Copy,143 Debug,144 Default,145 TypeInfo,146 MaxEncodedLen,147)]148#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]149pub struct CollectionId(pub u32);150impl EncodeLike<u32> for CollectionId {}151impl EncodeLike<CollectionId> for u32 {}152153#[derive(154 Encode,155 Decode,156 PartialEq,157 Eq,158 PartialOrd,159 Ord,160 Clone,161 Copy,162 Debug,163 Default,164 TypeInfo,165 MaxEncodedLen,166)]167#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]168pub struct TokenId(pub u32);169impl EncodeLike<u32> for TokenId {}170impl EncodeLike<TokenId> for u32 {}171172impl TokenId {173 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {174 self.0175 .checked_add(1)176 .ok_or(ArithmeticError::Overflow)177 .map(Self)178 }179}180181impl From<TokenId> for U256 {182 fn from(t: TokenId) -> Self {183 t.0.into()184 }185}186187impl TryFrom<U256> for TokenId {188 type Error = &'static str;189190 fn try_from(value: U256) -> Result<Self, Self::Error> {191 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))192 }193}194195#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]196#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]197pub struct TokenData<CrossAccountId> {198 pub const_data: Vec<u8>,199 pub properties: Vec<Property>,200 pub owner: Option<CrossAccountId>,201}202203pub struct OverflowError;204impl From<OverflowError> for &'static str {205 fn from(_: OverflowError) -> Self {206 "overflow occured"207 }208}209210pub type DecimalPoints = u8;211212#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]213#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]214pub enum CollectionMode {215 NFT,216 // decimal points217 Fungible(DecimalPoints),218 ReFungible,219}220221impl CollectionMode {222 pub fn id(&self) -> u8 {223 match self {224 CollectionMode::NFT => 1,225 CollectionMode::Fungible(_) => 2,226 CollectionMode::ReFungible => 3,227 }228 }229}230231pub trait SponsoringResolve<AccountId, Call> {232 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;233}234235#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]236#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]237pub enum AccessMode {238 Normal,239 AllowList,240}241impl Default for AccessMode {242 fn default() -> Self {243 Self::Normal244 }245}246247#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]248#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]249pub enum SchemaVersion {250 ImageURL,251 Unique,252}253impl Default for SchemaVersion {254 fn default() -> Self {255 Self::ImageURL256 }257}258259#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]260#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]261pub struct Ownership<AccountId> {262 pub owner: AccountId,263 pub fraction: u128,264}265266#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]267#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]268pub enum SponsorshipState<AccountId> {269 /// The fees are applied to the transaction sender270 Disabled,271 Unconfirmed(AccountId),272 /// Transactions are sponsored by specified account273 Confirmed(AccountId),274}275276impl<AccountId> SponsorshipState<AccountId> {277 pub fn sponsor(&self) -> Option<&AccountId> {278 match self {279 Self::Confirmed(sponsor) => Some(sponsor),280 _ => None,281 }282 }283284 pub fn pending_sponsor(&self) -> Option<&AccountId> {285 match self {286 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),287 _ => None,288 }289 }290291 pub fn confirmed(&self) -> bool {292 matches!(self, Self::Confirmed(_))293 }294}295296impl<T> Default for SponsorshipState<T> {297 fn default() -> Self {298 Self::Disabled299 }300}301302/// Used in storage303#[struct_versioning::versioned(version = 2, upper)]304#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]305pub struct Collection<AccountId> {306 pub owner: AccountId,307 pub mode: CollectionMode,308 pub access: AccessMode,309 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,310 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,311 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,312 pub mint_mode: bool,313314 #[version(..2)]315 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,316317 pub schema_version: SchemaVersion,318 pub sponsorship: SponsorshipState<AccountId>,319320 #[version(..2)]321 pub limits: CollectionLimitsVersion1, // Collection private restrictions322 #[version(2.., upper(limits.into()))]323 pub limits: CollectionLimitsVersion2,324325 #[version(..2)]326 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,327328 #[version(..2)]329 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,330331 #[version(..2)]332 pub meta_update_permission: MetaUpdatePermission,333}334335/// Used in RPC calls336#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]337#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]338pub struct RpcCollection<AccountId> {339 pub owner: AccountId,340 pub mode: CollectionMode,341 pub access: AccessMode,342 pub name: Vec<u16>,343 pub description: Vec<u16>,344 pub token_prefix: Vec<u8>,345 pub mint_mode: bool,346 pub offchain_schema: Vec<u8>,347 pub schema_version: SchemaVersion,348 pub sponsorship: SponsorshipState<AccountId>,349 pub limits: CollectionLimits,350 pub const_on_chain_schema: Vec<u8>,351 pub token_property_permissions: Vec<PropertyKeyPermission>,352 pub properties: Vec<Property>,353}354355#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]356#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]357pub enum CollectionField {358 ConstOnChainSchema,359 OffchainSchema,360}361362#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]363#[derivative(Debug, Default(bound = ""))]364pub struct CreateCollectionData<AccountId> {365 #[derivative(Default(value = "CollectionMode::NFT"))]366 pub mode: CollectionMode,367 pub access: Option<AccessMode>,368 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,369 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,370 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,371 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,372 pub schema_version: Option<SchemaVersion>,373 pub pending_sponsor: Option<AccountId>,374 pub limits: Option<CollectionLimits>,375 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,376 pub token_property_permissions: CollectionPropertiesPermissionsVec,377 pub properties: CollectionPropertiesVec,378}379380pub type CollectionPropertiesPermissionsVec =381 BoundedVec<PropertyKeyPermission, MaxPropertiesPermissionsEncodeLen>;382383pub type CollectionPropertiesVec =384 BoundedVec<Property, ConstU32<MAX_COLLECTION_PROPERTIES_ENCODE_LEN>>;385386/// All fields are wrapped in `Option`s, where None means chain default387#[struct_versioning::versioned(version = 2, upper)]388#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]389#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]390pub struct CollectionLimits {391 pub account_token_ownership_limit: Option<u32>,392 pub sponsored_data_size: Option<u32>,393394 /// FIXME should we delete this or repurpose it?395 /// None - setVariableMetadata is not sponsored396 /// Some(v) - setVariableMetadata is sponsored397 /// if there is v block between txs398 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,399 pub token_limit: Option<u32>,400401 // Timeouts for item types in passed blocks402 pub sponsor_transfer_timeout: Option<u32>,403 pub sponsor_approve_timeout: Option<u32>,404 pub owner_can_transfer: Option<bool>,405 pub owner_can_destroy: Option<bool>,406 pub transfers_enabled: Option<bool>,407408 #[version(2.., upper(None))]409 pub nesting_rule: Option<NestingRule>,410}411412impl CollectionLimits {413 pub fn account_token_ownership_limit(&self) -> u32 {414 self.account_token_ownership_limit415 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)416 .min(MAX_TOKEN_OWNERSHIP)417 }418 pub fn sponsored_data_size(&self) -> u32 {419 self.sponsored_data_size420 .unwrap_or(CUSTOM_DATA_LIMIT)421 .min(CUSTOM_DATA_LIMIT)422 }423 pub fn token_limit(&self) -> u32 {424 self.token_limit425 .unwrap_or(COLLECTION_TOKEN_LIMIT)426 .min(COLLECTION_TOKEN_LIMIT)427 }428 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {429 self.sponsor_transfer_timeout430 .unwrap_or(default)431 .min(MAX_SPONSOR_TIMEOUT)432 }433 pub fn sponsor_approve_timeout(&self) -> u32 {434 self.sponsor_approve_timeout435 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)436 .min(MAX_SPONSOR_TIMEOUT)437 }438 pub fn owner_can_transfer(&self) -> bool {439 self.owner_can_transfer.unwrap_or(true)440 }441 pub fn owner_can_destroy(&self) -> bool {442 self.owner_can_destroy.unwrap_or(true)443 }444 pub fn transfers_enabled(&self) -> bool {445 self.transfers_enabled.unwrap_or(true)446 }447 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {448 match self449 .sponsored_data_rate_limit450 .unwrap_or(SponsoringRateLimit::SponsoringDisabled)451 {452 SponsoringRateLimit::SponsoringDisabled => None,453 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),454 }455 }456 pub fn nesting_rule(&self) -> &NestingRule {457 static DEFAULT: NestingRule = NestingRule::Disabled;458 self.nesting_rule.as_ref().unwrap_or(&DEFAULT)459 }460}461462#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]463#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]464#[derivative(Debug)]465pub enum NestingRule {466 /// No one can nest tokens467 Disabled,468 /// Owner can nest any tokens469 Owner,470 /// Owner can nest tokens from specified collections471 OwnerRestricted(472 #[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]473 #[derivative(Debug(format_with = "bounded::set_debug"))]474 BoundedBTreeSet<CollectionId, ConstU32<16>>,475 ),476}477478#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]479#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]480pub enum SponsoringRateLimit {481 SponsoringDisabled,482 Blocks(u32),483}484485#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]486#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]487#[derivative(Debug)]488pub struct CreateNftData {489 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]490 #[derivative(Debug(format_with = "bounded::vec_debug"))]491 pub const_data: BoundedVec<u8, CustomDataLimit>,492493 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]494 #[derivative(Debug(format_with = "bounded::vec_debug"))]495 pub properties: CollectionPropertiesVec,496}497498#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]499#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]500pub struct CreateFungibleData {501 pub value: u128,502}503504#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]505#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]506#[derivative(Debug)]507pub struct CreateReFungibleData {508 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]509 #[derivative(Debug(format_with = "bounded::vec_debug"))]510 pub const_data: BoundedVec<u8, CustomDataLimit>,511 pub pieces: u128,512}513514#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]515pub enum MetaUpdatePermission {516 ItemOwner,517 Admin,518 None,519}520521#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]522#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]523pub enum CreateItemData {524 NFT(CreateNftData),525 Fungible(CreateFungibleData),526 ReFungible(CreateReFungibleData),527}528529#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]530#[derivative(Debug)]531pub struct CreateNftExData<CrossAccountId> {532 #[derivative(Debug(format_with = "bounded::vec_debug"))]533 pub const_data: BoundedVec<u8, CustomDataLimit>,534 #[derivative(Debug(format_with = "bounded::vec_debug"))]535 pub properties: CollectionPropertiesVec,536 pub owner: CrossAccountId,537}538539#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]540#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]541pub struct CreateRefungibleExData<CrossAccountId> {542 #[derivative(Debug(format_with = "bounded::vec_debug"))]543 pub const_data: BoundedVec<u8, CustomDataLimit>,544 #[derivative(Debug(format_with = "bounded::map_debug"))]545 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,546}547548#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]549#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]550pub enum CreateItemExData<CrossAccountId> {551 NFT(552 #[derivative(Debug(format_with = "bounded::vec_debug"))]553 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,554 ),555 Fungible(556 #[derivative(Debug(format_with = "bounded::map_debug"))]557 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,558 ),559 /// Many tokens, each may have only one owner560 RefungibleMultipleItems(561 #[derivative(Debug(format_with = "bounded::vec_debug"))]562 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,563 ),564 /// Single token, which may have many owners565 RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),566}567568impl CreateItemData {569 pub fn data_size(&self) -> usize {570 match self {571 CreateItemData::NFT(data) => data.const_data.len(),572 CreateItemData::ReFungible(data) => data.const_data.len(),573 _ => 0,574 }575 }576}577578impl From<CreateNftData> for CreateItemData {579 fn from(item: CreateNftData) -> Self {580 CreateItemData::NFT(item)581 }582}583584impl From<CreateReFungibleData> for CreateItemData {585 fn from(item: CreateReFungibleData) -> Self {586 CreateItemData::ReFungible(item)587 }588}589590impl From<CreateFungibleData> for CreateItemData {591 fn from(item: CreateFungibleData) -> Self {592 CreateItemData::Fungible(item)593 }594}595596#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]597#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]598pub struct CollectionStats {599 pub created: u32,600 pub destroyed: u32,601 pub alive: u32,602}603604#[derive(Encode, Decode, Clone, Debug)]605#[cfg_attr(feature = "std", derive(PartialEq))]606pub struct PhantomType<T>(core::marker::PhantomData<T>);607608impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {609 type Identity = PhantomType<T>;610611 fn type_info() -> scale_info::Type {612 use scale_info::{613 Type, Path,614 build::{FieldsBuilder, UnnamedFields},615 type_params,616 };617 Type::builder()618 .path(Path::new("up_data_structs", "PhantomType"))619 .type_params(type_params!(T))620 .composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))621 }622}623impl<T> MaxEncodedLen for PhantomType<T> {624 fn max_encoded_len() -> usize {625 0626 }627}628629pub type PropertyKey = BoundedVec<u8, ConstU32<MAX_PROPERTY_KEY_LENGTH>>;630pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;631632#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]633#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]634pub struct PropertyPermission {635 pub mutable: bool,636 pub collection_admin: bool,637 pub token_owner: bool,638}639640impl PropertyPermission {641 pub fn none() -> Self {642 Self {643 mutable: true,644 collection_admin: false,645 token_owner: false,646 }647 }648}649650#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]651#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]652pub struct Property {653 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]654 pub key: PropertyKey,655656 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]657 pub value: PropertyValue,658}659660impl Into<(PropertyKey, PropertyValue)> for Property {661 fn into(self) -> (PropertyKey, PropertyValue) {662 (self.key, self.value)663 }664}665666#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]667#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]668pub struct PropertyKeyPermission {669 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]670 pub key: PropertyKey,671672 pub permission: PropertyPermission,673}674675impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {676 fn into(self) -> (PropertyKey, PropertyPermission) {677 (self.key, self.permission)678 }679}680681#[derive(Debug)]682pub enum PropertiesError {683 NoSpaceForProperty,684 PropertyLimitReached,685 InvalidCharacterInPropertyKey,686 PropertyKeyIsTooLong,687 EmptyPropertyKey,688}689690#[derive(Clone, Copy)]691pub enum PropertyScope {692 None,693 Rmrk,694}695696impl PropertyScope {697 pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {698 let scope_str: &[u8] = match self {699 Self::None => return Ok(key),700 Self::Rmrk => b"rmrk",701 };702703 [scope_str, b":", key.as_slice()]704 .concat()705 .try_into()706 .map_err(|_| PropertiesError::PropertyKeyIsTooLong)707 }708}709710pub trait TrySetProperty: Sized {711 type Value;712713 fn try_scoped_set(714 &mut self,715 scope: PropertyScope,716 key: PropertyKey,717 value: Self::Value,718 ) -> Result<(), PropertiesError>;719720 fn try_scoped_set_from_iter<I, KV>(721 &mut self,722 scope: PropertyScope,723 iter: I,724 ) -> Result<(), PropertiesError>725 where726 I: Iterator<Item=KV>,727 KV: Into<(PropertyKey, Self::Value)>728 {729 for kv in iter {730 let (key, value) = kv.into();731 self.try_scoped_set(scope, key, value)?;732 }733734 Ok(())735 }736737 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {738 self.try_scoped_set(PropertyScope::None, key, value)739 }740741 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>742 where743 I: Iterator<Item=KV>,744 KV: Into<(PropertyKey, Self::Value)>745 {746 self.try_scoped_set_from_iter(PropertyScope::None, iter)747 }748}749750#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]751#[derivative(Default(bound = ""))]752pub struct PropertiesMap<Value>(753 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,754);755756impl<Value> PropertiesMap<Value> {757 pub fn new() -> Self {758 Self(BoundedBTreeMap::new())759 }760761 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {762 Self::check_property_key(key)?;763764 Ok(self.0.remove(key))765 }766767 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {768 self.0.get(key)769 }770771 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &Value)> {772 self.0.iter()773 }774775 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {776 if key.is_empty() {777 return Err(PropertiesError::EmptyPropertyKey);778 }779780 for byte in key.as_slice().iter() {781 let byte = *byte;782783 if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' {784 return Err(PropertiesError::InvalidCharacterInPropertyKey);785 }786 }787788 Ok(())789 }790}791792impl<Value> TrySetProperty for PropertiesMap<Value> {793 type Value = Value;794795 fn try_scoped_set(796 &mut self,797 scope: PropertyScope,798 key: PropertyKey,799 value: Self::Value,800 ) -> Result<(), PropertiesError> {801 Self::check_property_key(&key)?;802803 let key = scope.apply(key)?;804 self.0805 .try_insert(key, value)806 .map_err(|_| PropertiesError::PropertyLimitReached)?;807808 Ok(())809 }810}811812pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;813814#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]815pub struct Properties {816 map: PropertiesMap<PropertyValue>,817 consumed_space: u32,818 space_limit: u32,819}820821impl Properties {822 pub fn new(space_limit: u32) -> Self {823 Self {824 map: PropertiesMap::new(),825 consumed_space: 0,826 space_limit,827 }828 }829830 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {831 let value = self.map.remove(key)?;832833 if let Some(ref value) = value {834 let value_len = value.len() as u32;835 self.consumed_space -= value_len;836 }837838 Ok(value)839 }840841 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {842 self.map.get(key)843 }844845 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {846 self.map.iter()847 }848}849850impl TrySetProperty for Properties {851 type Value = PropertyValue;852853 fn try_scoped_set(854 &mut self,855 scope: PropertyScope,856 key: PropertyKey,857 value: Self::Value,858 ) -> Result<(), PropertiesError> {859 let value_len = value.len();860861 if self.consumed_space as usize + value_len > self.space_limit as usize {862 return Err(PropertiesError::NoSpaceForProperty);863 }864865 self.map.try_scoped_set(scope, key, value)?;866867 self.consumed_space += value_len as u32;868869 Ok(())870 }871}872873pub struct CollectionProperties;874875impl Get<Properties> for CollectionProperties {876 fn get() -> Properties {877 Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)878 }879}880881pub struct TokenProperties;882883impl Get<Properties> for TokenProperties {884 fn get() -> Properties {885 Properties::new(MAX_TOKEN_PROPERTIES_SIZE)886 }887}888889// RMRK890// todo document?891parameter_types! {892 #[derive(PartialEq, TypeInfo)]893 pub const RmrkStringLimit: u32 = 128;894 #[derive(PartialEq)]895 pub const RmrkCollectionSymbolLimit: u32 = 100;896 #[derive(PartialEq)]897 pub const RmrkResourceSymbolLimit: u32 = 10;898 #[derive(PartialEq)]899 pub const RmrkKeyLimit: u32 = 32;900 #[derive(PartialEq)]901 pub const RmrkValueLimit: u32 = 256;902 #[derive(PartialEq)]903 pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;904 #[derive(PartialEq)]905 pub const RmrkPartsLimit: u32 = 3;906}907908impl From<RmrkCollectionId> for CollectionId {909 fn from(id: RmrkCollectionId) -> Self {910 Self(id)911 }912}913914impl From<RmrkNftId> for TokenId {915 fn from(id: RmrkNftId) -> Self {916 Self(id)917 }918}919920pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;921pub type RmrkCollectionInfo<AccountId> = CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;922pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;923pub type RmrkResourceInfo = ResourceInfo<924 BoundedVec<u8, RmrkResourceSymbolLimit>,925 RmrkString,926 BoundedVec<RmrkPartId, RmrkPartsLimit>,927>;928pub type RmrkPropertyInfo =929 PropertyInfo<BoundedVec<u8, RmrkKeyLimit>, BoundedVec<u8, RmrkValueLimit>>;930pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;931pub type RmrkPartType =932 PartType<RmrkString, BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>>;933pub type RmrkTheme = Theme<RmrkString, Vec<ThemeProperty<RmrkString>>>;934935pub type RmrkRpcString = Vec<u8>;936pub type RmrkThemeName = RmrkRpcString;937pub type RmrkPropertyKey = RmrkRpcString;938939pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;runtime/opal/Cargo.tomldiffbeforeafterboth--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -33,7 +33,7 @@
'pallet-fungible/runtime-benchmarks',
'pallet-refungible/runtime-benchmarks',
'pallet-nonfungible/runtime-benchmarks',
- 'pallet-rmrk-proxy/runtime-benchmarks',
+ 'pallet-proxy-rmrk-core/runtime-benchmarks',
'pallet-unique/runtime-benchmarks',
'pallet-inflation/runtime-benchmarks',
'pallet-xcm/runtime-benchmarks',
@@ -90,7 +90,7 @@
'pallet-fungible/std',
'pallet-refungible/std',
'pallet-nonfungible/std',
- 'pallet-rmrk-proxy/std',
+ 'pallet-proxy-rmrk-core/std',
'pallet-unique/std',
'pallet-unq-scheduler/std',
'pallet-charge-transaction/std',
@@ -417,7 +417,7 @@
pallet-fungible = { default-features = false, path = "../../pallets/fungible" }
pallet-refungible = { default-features = false, path = "../../pallets/refungible" }
pallet-nonfungible = { default-features = false, path = "../../pallets/nonfungible" }
-pallet-rmrk-proxy = { default-features = false, path = "../../pallets/rmrk-proxy" }
+pallet-proxy-rmrk-core = { default-features = false, path = "../../pallets/proxy-rmrk-core", package = "pallet-rmrk-core" }
pallet-unq-scheduler = { path = '../../pallets/scheduler', default-features = false }
# pallet-contract-helpers = { path = '../pallets/contract-helpers', default-features = false, version = '0.1.0' }
pallet-charge-transaction = { git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.21", package = "pallet-template-transaction-payment", default-features = false, version = "3.0.0" }
runtime/opal/src/lib.rsdiffbeforeafterboth--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -901,7 +901,7 @@
type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;
}
-impl pallet_rmrk_proxy::Config for Runtime {
+impl pallet_proxy_rmrk_core::Config for Runtime {
type Event = Event;
}
@@ -1017,7 +1017,7 @@
Refungible: pallet_refungible::{Pallet, Storage} = 68,
Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,
Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,
- RmrkProxy: pallet_rmrk_proxy::{Pallet, Call, Storage, Event<T>} = 71,
+ ProxyRmrkCore: pallet_proxy_rmrk_core::{Pallet, Call, Storage, Event<T>} = 71,
// Frontier
EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,
runtime/quartz/Cargo.tomldiffbeforeafterboth--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -33,6 +33,7 @@
'pallet-fungible/runtime-benchmarks',
'pallet-refungible/runtime-benchmarks',
'pallet-nonfungible/runtime-benchmarks',
+ 'pallet-proxy-rmrk-core/runtime-benchmarks',
'pallet-unique/runtime-benchmarks',
'pallet-inflation/runtime-benchmarks',
'pallet-xcm/runtime-benchmarks',
@@ -89,6 +90,7 @@
'pallet-fungible/std',
'pallet-refungible/std',
'pallet-nonfungible/std',
+ 'pallet-proxy-rmrk-core/std',
'pallet-unique/std',
'pallet-unq-scheduler/std',
'pallet-charge-transaction/std',
@@ -414,6 +416,7 @@
pallet-fungible = { default-features = false, path = "../../pallets/fungible" }
pallet-refungible = { default-features = false, path = "../../pallets/refungible" }
pallet-nonfungible = { default-features = false, path = "../../pallets/nonfungible" }
+pallet-proxy-rmrk-core = { default-features = false, path = "../../pallets/proxy-rmrk-core", package = "pallet-rmrk-core" }
pallet-unq-scheduler = { path = '../../pallets/scheduler', default-features = false }
# pallet-contract-helpers = { path = '../pallets/contract-helpers', default-features = false, version = '0.1.0' }
pallet-charge-transaction = { git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.21", package = "pallet-template-transaction-payment", default-features = false, version = "3.0.0" }
runtime/unique/Cargo.tomldiffbeforeafterboth--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -33,6 +33,7 @@
'pallet-fungible/runtime-benchmarks',
'pallet-refungible/runtime-benchmarks',
'pallet-nonfungible/runtime-benchmarks',
+ 'pallet-proxy-rmrk-core/runtime-benchmarks',
'pallet-unique/runtime-benchmarks',
'pallet-inflation/runtime-benchmarks',
'pallet-xcm/runtime-benchmarks',
@@ -89,6 +90,7 @@
'pallet-fungible/std',
'pallet-refungible/std',
'pallet-nonfungible/std',
+ 'pallet-proxy-rmrk-core/std',
'pallet-unique/std',
'pallet-unq-scheduler/std',
'pallet-charge-transaction/std',
@@ -413,6 +415,7 @@
pallet-fungible = { default-features = false, path = "../../pallets/fungible" }
pallet-refungible = { default-features = false, path = "../../pallets/refungible" }
pallet-nonfungible = { default-features = false, path = "../../pallets/nonfungible" }
+pallet-proxy-rmrk-core = { default-features = false, path = "../../pallets/proxy-rmrk-core", package = "pallet-rmrk-core" }
pallet-unq-scheduler = { path = '../../pallets/scheduler', default-features = false }
# pallet-contract-helpers = { path = '../pallets/contract-helpers', default-features = false, version = '0.1.0' }
pallet-charge-transaction = { git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.21", package = "pallet-template-transaction-payment", default-features = false, version = "3.0.0" }