difftreelog
Merge branch 'UniqueNetwork:develop' into develop
in: master
4 files changed
primitives/data-structs/src/bounded.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//! This module contins implementations for support bounded structures ([`BoundedVec`], [`BoundedBTreeMap`], [`BoundedBTreeSet`]) in [`serde`].181use core::fmt;19use core::fmt;2use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet};20use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet};7 storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},25 storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},8};26};92710/// BoundedVec doesn't supports serde28/// [`serde`] implementations for [`BoundedVec`].11#[cfg(feature = "serde1")]29#[cfg(feature = "serde1")]12pub mod vec_serde {30pub mod vec_serde {13 use core::convert::TryFrom;31 use core::convert::TryFrom;39 }57 }40}58}415960/// Format [`BoundedVec`] for debug output.42pub fn vec_debug<V, S>(v: &BoundedVec<V, S>, f: &mut fmt::Formatter) -> Result<(), fmt::Error>61pub fn vec_debug<V, S>(v: &BoundedVec<V, S>, f: &mut fmt::Formatter) -> Result<(), fmt::Error>43where62where44 V: fmt::Debug,63 V: fmt::Debug,496850#[cfg(feature = "serde1")]69#[cfg(feature = "serde1")]51#[allow(dead_code)]70#[allow(dead_code)]71/// [`serde`] implementations for [`BoundedBTreeMap`].52pub mod map_serde {72pub mod map_serde {53 use core::convert::TryFrom;73 use core::convert::TryFrom;54 use sp_std::collections::btree_map::BTreeMap;74 use sp_std::collections::btree_map::BTreeMap;84 }104 }85}105}86106107/// Format [`BoundedBTreeMap`] for debug output.87pub fn map_debug<K, V, S>(108pub fn map_debug<K, V, S>(88 v: &BoundedBTreeMap<K, V, S>,109 v: &BoundedBTreeMap<K, V, S>,89 f: &mut fmt::Formatter,110 f: &mut fmt::Formatter,9811999#[cfg(feature = "serde1")]120#[cfg(feature = "serde1")]100#[allow(dead_code)]121#[allow(dead_code)]122/// [`serde`] implementations for [`BoundedBTreeSet`].101pub mod set_serde {123pub mod set_serde {102 use core::convert::TryFrom;124 use core::convert::TryFrom;103 use sp_std::collections::btree_set::BTreeSet;125 use sp_std::collections::btree_set::BTreeSet;129 }151 }130}152}131153154/// Format [`BoundedBTreeSet`] for debug output.132pub fn set_debug<K, S>(v: &BoundedBTreeSet<K, S>, f: &mut fmt::Formatter) -> Result<(), fmt::Error>155pub fn set_debug<K, S>(v: &BoundedBTreeSet<K, S>, f: &mut fmt::Formatter) -> Result<(), fmt::Error>133where156where134 K: fmt::Debug + Ord,157 K: fmt::Debug + Ord,primitives/data-structs/src/lib.rsdiffbeforeafterboth14// You should have received a copy of the GNU General Public License14// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Primitives crate.18//!19//! This crate contains types, traits and constants.162017#![cfg_attr(not(feature = "std"), no_std)]21#![cfg_attr(not(feature = "std"), no_std)]182255pub mod mapping;59pub mod mapping;56mod migration;60mod migration;576162/// Maximum of decimal points.58pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;63pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;6465/// Maximum pieces for refungible token.59pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;66pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;60pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;67pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;616869/// Maximum tokens for user.62pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {70pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {63 100_00071 100_00064} else {72} else {65 1073 1066};74};7576/// Maximum for collections can be created.67pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {77pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {68 100_00078 100_00069} else {79} else {70 1080 1071};81};8283/// Maximum for various custom data of token.72pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {84pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {73 204885 204874} else {86} else {75 1087 1076};88};8990/// Maximum admins per collection.77pub const COLLECTION_ADMINS_LIMIT: u32 = 5;91pub const COLLECTION_ADMINS_LIMIT: u32 = 5;9293/// Maximum tokens per collection.78pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;94pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;9596/// Maximum tokens per account.79pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {97pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {80 1_000_00098 1_000_00081} else {99} else {82 10100 1083};101};8410285// Timeouts for item types in passed blocks103/// Default timeout for transfer sponsoring NFT item.86pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;104pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;105/// Default timeout for transfer sponsoring fungible item.87pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;106pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;107/// Default timeout for transfer sponsoring refungible item.88pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;108pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;89109110/// Default timeout for sponsored approving.90pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;111pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;9111292// Schema limits113// Schema limits93pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;114pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;94pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;115pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;95pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;116pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;96117118// TODO: not used. Delete?97pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;119pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;98120121/// Maximum length for collection name.99pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;122pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;123124/// Maximum length for collection description.100pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;125pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;126127/// Maximal token prefix length.101pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;128pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;102129130/// Maximal lenght of property key.103pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;131pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;132133/// Maximal lenght of property value.104pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;134pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;135136/// Maximum properties that can be assigned to token.105pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;137pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;106138139/// Maximal lenght of extended property value.107pub const MAX_AUX_PROPERTY_VALUE_LENGTH: u32 = 2048;140pub const MAX_AUX_PROPERTY_VALUE_LENGTH: u32 = 2048;108141142/// Maximum size for all collection properties.109pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;143pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;144145/// Maximum size for all token properties.110pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;146pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;111147112/// How much items can be created per single148/// How much items can be created per single113/// create_many call149/// create_many call.114pub const MAX_ITEMS_PER_BATCH: u32 = 200;150pub const MAX_ITEMS_PER_BATCH: u32 = 200;115151152/// Used for limit bounded types of token custom data.116pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;153pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;117154155/// Collection id.118#[derive(156#[derive(119 Encode,157 Encode,120 Decode,158 Decode,134impl EncodeLike<u32> for CollectionId {}172impl EncodeLike<u32> for CollectionId {}135impl EncodeLike<CollectionId> for u32 {}173impl EncodeLike<CollectionId> for u32 {}136174175/// Token id.137#[derive(176#[derive(138 Encode,177 Encode,139 Decode,178 Decode,154impl EncodeLike<TokenId> for u32 {}193impl EncodeLike<TokenId> for u32 {}155194156impl TokenId {195impl TokenId {196 /// Try to get next token id.197 ///198 /// If next id cause overflow, then [`ArithmeticError::Overflow`] returned.157 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {199 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {158 self.0200 self.0159 .checked_add(1)201 .checked_add(1)176 }218 }177}219}178220221/// Token data.179#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]222#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]180#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]223#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]181pub struct TokenData<CrossAccountId> {224pub struct TokenData<CrossAccountId> {225 /// Properties of token.182 pub properties: Vec<Property>,226 pub properties: Vec<Property>,227228 /// Token owner.183 pub owner: Option<CrossAccountId>,229 pub owner: Option<CrossAccountId>,230231 /// Token pieces.184 pub pieces: u128,232 pub pieces: u128,185}233}186234235// TODO: unused type187pub struct OverflowError;236pub struct OverflowError;188impl From<OverflowError> for &'static str {237impl From<OverflowError> for &'static str {189 fn from(_: OverflowError) -> Self {238 fn from(_: OverflowError) -> Self {190 "overflow occured"239 "overflow occured"191 }240 }192}241}193242243/// Alias for decimal points type.194pub type DecimalPoints = u8;244pub type DecimalPoints = u8;195245246/// Collection mode.247///248/// Collection can represent various types of tokens.249/// Each collection can contain only one type of tokens at a time.250/// This type helps to understand which tokens the collection contains.196#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]251#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]197#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]252#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]198pub enum CollectionMode {253pub enum CollectionMode {254 /// Non fungible tokens.199 NFT,255 NFT,256 /// Fungible tokens.200 Fungible(DecimalPoints),257 Fungible(DecimalPoints),258 /// Refungible tokens.201 ReFungible,259 ReFungible,202}260}203261204impl CollectionMode {262impl CollectionMode {263 /// Get collection mod as number.205 pub fn id(&self) -> u8 {264 pub fn id(&self) -> u8 {206 match self {265 match self {207 CollectionMode::NFT => 1,266 CollectionMode::NFT => 1,211 }270 }212}271}213272273// TODO: unused trait214pub trait SponsoringResolve<AccountId, Call> {274pub trait SponsoringResolve<AccountId, Call> {215 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;275 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;216}276}217277278/// Access mode for some token operations.218#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]279#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]219#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]280#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]220pub enum AccessMode {281pub enum AccessMode {282 /// Access grant for owner and admins. Used as default.221 Normal,283 Normal,284 /// Like a [`Normal`](AccessMode::Normal) but also users in allow list.222 AllowList,285 AllowList,223}286}224impl Default for AccessMode {287impl Default for AccessMode {227 }290 }228}291}229292293// TODO: remove in future.230#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]294#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]231#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]295#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]232pub enum SchemaVersion {296pub enum SchemaVersion {239 }303 }240}304}241305306// TODO: unused type242#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]307#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]243#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]308#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]244pub struct Ownership<AccountId> {309pub struct Ownership<AccountId> {245 pub owner: AccountId,310 pub owner: AccountId,246 pub fraction: u128,311 pub fraction: u128,247}312}248313314/// The state of collection sponsorship.249#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]315#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]250#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]316#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]251pub enum SponsorshipState<AccountId> {317pub enum SponsorshipState<AccountId> {252 /// The fees are applied to the transaction sender318 /// The fees are applied to the transaction sender.253 Disabled,319 Disabled,254 /// Pending confirmation from a sponsor-to-be320 /// The sponsor is under consideration. Until the sponsor gives his consent,321 /// the fee will still be charged to sender.255 Unconfirmed(AccountId),322 Unconfirmed(AccountId),256 /// Transactions are sponsored by specified account323 /// Transactions are sponsored by specified account.257 Confirmed(AccountId),324 Confirmed(AccountId),258}325}259326260impl<AccountId> SponsorshipState<AccountId> {327impl<AccountId> SponsorshipState<AccountId> {261 /// Get the acting sponsor account, if present328 /// Get a sponsor of the collection who has confirmed his status.262 pub fn sponsor(&self) -> Option<&AccountId> {329 pub fn sponsor(&self) -> Option<&AccountId> {263 match self {330 match self {264 Self::Confirmed(sponsor) => Some(sponsor),331 Self::Confirmed(sponsor) => Some(sponsor),265 _ => None,332 _ => None,266 }333 }267 }334 }268335269 /// Get the sponsor account currently pending confirmation, if present336 /// Get a sponsor of the collection who has pending or confirmed status.270 pub fn pending_sponsor(&self) -> Option<&AccountId> {337 pub fn pending_sponsor(&self) -> Option<&AccountId> {271 match self {338 match self {272 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),339 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),273 _ => None,340 _ => None,274 }341 }275 }342 }276343277 /// Is sponsorship set and acting344 /// Whether the sponsorship is confirmed.278 pub fn confirmed(&self) -> bool {345 pub fn confirmed(&self) -> bool {279 matches!(self, Self::Confirmed(_))346 matches!(self, Self::Confirmed(_))280 }347 }290pub type CollectionDescription = BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>;357pub type CollectionDescription = BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>;291pub type CollectionTokenPrefix = BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>;358pub type CollectionTokenPrefix = BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>;292359360/// Base structure for represent collection.361///362/// Used to provide basic functionality for all types of collections.363///364/// #### Note293/// Collection parameters, used in storage (see [`RpcCollection`] for the RPC version).365/// Collection parameters, used in storage (see [`RpcCollection`] for the RPC version).294#[struct_versioning::versioned(version = 2, upper)]366#[struct_versioning::versioned(version = 2, upper)]295#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]367#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]296pub struct Collection<AccountId> {368pub struct Collection<AccountId> {369 /// Collection owner account.297 pub owner: AccountId,370 pub owner: AccountId,371372 /// Collection mode.298 pub mode: CollectionMode,373 pub mode: CollectionMode,374375 /// Access mode.299 #[version(..2)]376 #[version(..2)]300 pub access: AccessMode,377 pub access: AccessMode,378379 /// Collection name.301 pub name: CollectionName,380 pub name: CollectionName,381382 /// Collection description.302 pub description: CollectionDescription,383 pub description: CollectionDescription,384385 /// Token prefix.303 pub token_prefix: CollectionTokenPrefix,386 pub token_prefix: CollectionTokenPrefix,304387305 #[version(..2)]388 #[version(..2)]311 #[version(..2)]394 #[version(..2)]312 pub schema_version: SchemaVersion,395 pub schema_version: SchemaVersion,396397 /// The state of sponsorship of the collection.313 pub sponsorship: SponsorshipState<AccountId>,398 pub sponsorship: SponsorshipState<AccountId>,314399400 /// Collection limits.315 pub limits: CollectionLimits,401 pub limits: CollectionLimits,316402403 /// Collection permissions.317 #[version(2.., upper(Default::default()))]404 #[version(2.., upper(Default::default()))]318 pub permissions: CollectionPermissions,405 pub permissions: CollectionPermissions,319406335#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]422#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]336#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]423#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]337pub struct RpcCollection<AccountId> {424pub struct RpcCollection<AccountId> {425 /// Collection owner account.338 pub owner: AccountId,426 pub owner: AccountId,427428 /// Collection mode.339 pub mode: CollectionMode,429 pub mode: CollectionMode,430431 /// Collection name.340 pub name: Vec<u16>,432 pub name: Vec<u16>,433434 /// Collection description.341 pub description: Vec<u16>,435 pub description: Vec<u16>,436437 /// Token prefix.342 pub token_prefix: Vec<u8>,438 pub token_prefix: Vec<u8>,439440 /// The state of sponsorship of the collection.343 pub sponsorship: SponsorshipState<AccountId>,441 pub sponsorship: SponsorshipState<AccountId>,442443 /// Collection limits.344 pub limits: CollectionLimits,444 pub limits: CollectionLimits,445446 /// Collection permissions.345 pub permissions: CollectionPermissions,447 pub permissions: CollectionPermissions,448449 /// Token property permissions.346 pub token_property_permissions: Vec<PropertyKeyPermission>,450 pub token_property_permissions: Vec<PropertyKeyPermission>,451452 /// Collection properties.347 pub properties: Vec<Property>,453 pub properties: Vec<Property>,454455 /// Is collection read only.348 pub read_only: bool,456 pub read_only: bool,349}457}350458459/// Data used for create collection.460///461/// All fields are wrapped in [`Option`], where `None` means chain default.351#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]462#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]352#[derivative(Debug, Default(bound = ""))]463#[derivative(Debug, Default(bound = ""))]353pub struct CreateCollectionData<AccountId> {464pub struct CreateCollectionData<AccountId> {465 /// Collection mode.354 #[derivative(Default(value = "CollectionMode::NFT"))]466 #[derivative(Default(value = "CollectionMode::NFT"))]355 pub mode: CollectionMode,467 pub mode: CollectionMode,468469 /// Access mode.356 pub access: Option<AccessMode>,470 pub access: Option<AccessMode>,471472 /// Collection name.357 pub name: CollectionName,473 pub name: CollectionName,474475 /// Collection description.358 pub description: CollectionDescription,476 pub description: CollectionDescription,477478 /// Token prefix.359 pub token_prefix: CollectionTokenPrefix,479 pub token_prefix: CollectionTokenPrefix,480481 /// Pending collection sponsor.360 pub pending_sponsor: Option<AccountId>,482 pub pending_sponsor: Option<AccountId>,483484 /// Collection limits.361 pub limits: Option<CollectionLimits>,485 pub limits: Option<CollectionLimits>,486487 /// Collection permissions.362 pub permissions: Option<CollectionPermissions>,488 pub permissions: Option<CollectionPermissions>,489490 /// Token property permissions.363 pub token_property_permissions: CollectionPropertiesPermissionsVec,491 pub token_property_permissions: CollectionPropertiesPermissionsVec,492493 /// Collection properties.364 pub properties: CollectionPropertiesVec,494 pub properties: CollectionPropertiesVec,365}495}366496497/// Bounded vector of properties permissions. Max length is [`MAX_PROPERTIES_PER_ITEM`].498// TODO: maybe rename to PropertiesPermissionsVec367pub type CollectionPropertiesPermissionsVec =499pub type CollectionPropertiesPermissionsVec =368 BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;500 BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;369501502/// Bounded vector of properties. Max length is [`MAX_PROPERTIES_PER_ITEM`].370pub type CollectionPropertiesVec = BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;503pub type CollectionPropertiesVec = BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;371504372/// Limits and restrictions of a collection.505/// Limits and restrictions of a collection.506///373/// All fields are wrapped in `Option`s, where None means chain default.507/// All fields are wrapped in [`Option`], where `None` means chain default.374///508///375/// todo:doc links to chain defaults509/// Update with `pallet_common::Pallet::clamp_limits`.376// IMPORTANT: When adding/removing fields from this struct - don't forget to also510// IMPORTANT: When adding/removing fields from this struct - don't forget to also377// update clamp_limits() in pallet-common.378#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]511#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]379#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]512#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]513// When adding/removing fields from this struct - don't forget to also update with `pallet_common::Pallet::clamp_limits`.514// TODO: move `pallet_common::Pallet::clamp_limits` into `impl CollectionLimits`.515// TODO: may be remove [`Option`] and **pub** from fields and create struct with default values.380pub struct CollectionLimits {516pub struct CollectionLimits {381 /// Maximum number of owned tokens per account. Chain default: [`ACCOUNT_TOKEN_OWNERSHIP_LIMIT`]517 /// How many tokens can a user have on one account.518 /// * Default - [`ACCOUNT_TOKEN_OWNERSHIP_LIMIT`].519 /// * Limit - [`MAX_TOKEN_OWNERSHIP`].382 pub account_token_ownership_limit: Option<u32>,520 pub account_token_ownership_limit: Option<u32>,383 /// Maximum size of data in bytes of a sponsored transaction. Chain default: [`CUSTOM_DATA_LIMIT`]521522 /// How many bytes of data are available for sponsorship.523 /// * Default - [`CUSTOM_DATA_LIMIT`].524 /// * Limit - [`CUSTOM_DATA_LIMIT`].384 pub sponsored_data_size: Option<u32>,525 pub sponsored_data_size: Option<u32>,385526386 /// FIXME should we delete this or repurpose it?527 // FIXME should we delete this or repurpose it?387 /// None - setVariableMetadata is not sponsored528 /// Times in how many blocks we sponsor data.388 /// Some(v) - setVariableMetadata is sponsored529 ///389 /// if there is v block between txs530 /// If is `Some(v)` then **setVariableMetadata** is sponsored if there is `v` block between transactions.531 ///532 /// * Default - [`SponsoringDisabled`](SponsoringRateLimit::SponsoringDisabled).533 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].390 ///534 ///391 /// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]535 /// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]392 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,536 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,393 /// Maximum amount of tokens inside the collection. Chain default: [`COLLECTION_TOKEN_LIMIT`]537 /// Maximum amount of tokens inside the collection. Chain default: [`COLLECTION_TOKEN_LIMIT`]538539 /// How many tokens can be mined into this collection.540 ///541 /// * Default - [`COLLECTION_TOKEN_LIMIT`].542 /// * Limit - [`COLLECTION_TOKEN_LIMIT`].394 pub token_limit: Option<u32>,543 pub token_limit: Option<u32>,395544396 /// Timeout for sponsoring a token transfer in passed blocks. Chain default:545 /// Timeouts for transfer sponsoring.397 /// either [`NFT_SPONSOR_TRANSFER_TIMEOUT`], [`FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`], or [`REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`],546 ///398 /// depending on the collection type.547 /// * Default548 /// - **Fungible** - [`FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`]549 /// - **NFT** - [`NFT_SPONSOR_TRANSFER_TIMEOUT`]550 /// - **Refungible** - [`REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`]551 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].399 pub sponsor_transfer_timeout: Option<u32>,552 pub sponsor_transfer_timeout: Option<u32>,553400 /// Timeout for sponsoring an approval in passed blocks. Chain default: [`SPONSOR_APPROVE_TIMEOUT`]554 /// Timeout for sponsoring an approval in passed blocks.555 ///556 /// * Default - [`SPONSOR_APPROVE_TIMEOUT`].557 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].401 pub sponsor_approve_timeout: Option<u32>,558 pub sponsor_approve_timeout: Option<u32>,402 /// Can a token be transferred by the owner. Chain default: `false`559560 /// Whether the collection owner of the collection can send tokens (which belong to other users).561 ///562 /// * Default - **false**.403 pub owner_can_transfer: Option<bool>,563 pub owner_can_transfer: Option<bool>,404 /// Can a token be burned by the owner. Chain default: `true`564565 /// Can the collection owner burn other people's tokens.566 ///567 /// * Default - **true**.405 pub owner_can_destroy: Option<bool>,568 pub owner_can_destroy: Option<bool>,406 /// Can a token be transferred at all. Chain default: `true`569570 /// Is it possible to send tokens from this collection between users.571 ///572 /// * Default - **true**.407 pub transfers_enabled: Option<bool>,573 pub transfers_enabled: Option<bool>,408}574}409575410impl CollectionLimits {576impl CollectionLimits {577 /// Get effective value for [`account_token_ownership_limit`](self.account_token_ownership_limit).411 pub fn account_token_ownership_limit(&self) -> u32 {578 pub fn account_token_ownership_limit(&self) -> u32 {412 self.account_token_ownership_limit579 self.account_token_ownership_limit413 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)580 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)414 .min(MAX_TOKEN_OWNERSHIP)581 .min(MAX_TOKEN_OWNERSHIP)415 }582 }583584 /// Get effective value for [`sponsored_data_size`](self.sponsored_data_size).416 pub fn sponsored_data_size(&self) -> u32 {585 pub fn sponsored_data_size(&self) -> u32 {417 self.sponsored_data_size586 self.sponsored_data_size418 .unwrap_or(CUSTOM_DATA_LIMIT)587 .unwrap_or(CUSTOM_DATA_LIMIT)419 .min(CUSTOM_DATA_LIMIT)588 .min(CUSTOM_DATA_LIMIT)420 }589 }590591 /// Get effective value for [`token_limit`](self.token_limit).421 pub fn token_limit(&self) -> u32 {592 pub fn token_limit(&self) -> u32 {422 self.token_limit593 self.token_limit423 .unwrap_or(COLLECTION_TOKEN_LIMIT)594 .unwrap_or(COLLECTION_TOKEN_LIMIT)424 .min(COLLECTION_TOKEN_LIMIT)595 .min(COLLECTION_TOKEN_LIMIT)425 }596 }597598 // TODO: may be replace u32 to mode?599 /// Get effective value for [`sponsor_transfer_timeout`](self.sponsor_transfer_timeout).426 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {600 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {427 self.sponsor_transfer_timeout601 self.sponsor_transfer_timeout428 .unwrap_or(default)602 .unwrap_or(default)429 .min(MAX_SPONSOR_TIMEOUT)603 .min(MAX_SPONSOR_TIMEOUT)430 }604 }605606 /// Get effective value for [`sponsor_approve_timeout`](self.sponsor_approve_timeout).431 pub fn sponsor_approve_timeout(&self) -> u32 {607 pub fn sponsor_approve_timeout(&self) -> u32 {432 self.sponsor_approve_timeout608 self.sponsor_approve_timeout433 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)609 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)434 .min(MAX_SPONSOR_TIMEOUT)610 .min(MAX_SPONSOR_TIMEOUT)435 }611 }612613 /// Get effective value for [`owner_can_transfer`](self.owner_can_transfer).436 pub fn owner_can_transfer(&self) -> bool {614 pub fn owner_can_transfer(&self) -> bool {437 self.owner_can_transfer.unwrap_or(false)615 self.owner_can_transfer.unwrap_or(false)438 }616 }617618 /// Get effective value for [`owner_can_transfer_instaled`](self.owner_can_transfer_instaled).439 pub fn owner_can_transfer_instaled(&self) -> bool {619 pub fn owner_can_transfer_instaled(&self) -> bool {440 self.owner_can_transfer.is_some()620 self.owner_can_transfer.is_some()441 }621 }622623 /// Get effective value for [`owner_can_destroy`](self.owner_can_destroy).442 pub fn owner_can_destroy(&self) -> bool {624 pub fn owner_can_destroy(&self) -> bool {443 self.owner_can_destroy.unwrap_or(true)625 self.owner_can_destroy.unwrap_or(true)444 }626 }627628 /// Get effective value for [`transfers_enabled`](self.transfers_enabled).445 pub fn transfers_enabled(&self) -> bool {629 pub fn transfers_enabled(&self) -> bool {446 self.transfers_enabled.unwrap_or(true)630 self.transfers_enabled.unwrap_or(true)447 }631 }632633 /// Get effective value for [`sponsored_data_rate_limit`](self.sponsored_data_rate_limit).448 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {634 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {449 match self635 match self450 .sponsored_data_rate_limit636 .sponsored_data_rate_limit457}643}458644459/// Permissions on certain operations within a collection.645/// Permissions on certain operations within a collection.646///460/// All fields are wrapped in `Option`s, where None means chain default.647/// Some fields are wrapped in [`Option`], where `None` means chain default.461// IMPORTANT: When adding/removing fields from this struct - don't forget to also648///462// update clamp_limits() in pallet-common.649/// Update with `pallet_common::Pallet::clamp_permissions`.463#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]650#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]464#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]651#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]652// When adding/removing fields from this struct - don't forget to also update `pallet_common::Pallet::clamp_permissions`.653// TODO: move `pallet_common::Pallet::clamp_permissions` into `impl CollectionPermissions`.465pub struct CollectionPermissions {654pub struct CollectionPermissions {655 /// Access mode.656 ///657 /// * Default - [`AccessMode::Normal`].466 pub access: Option<AccessMode>,658 pub access: Option<AccessMode>,659660 /// Minting allowance.661 ///662 /// * Default - **false**.467 pub mint_mode: Option<bool>,663 pub mint_mode: Option<bool>,664665 /// Permissions for nesting.666 ///667 /// * Default668 /// - `token_owner` - **false**669 /// - `collection_admin` - **false**670 /// - `restricted` - **None**468 pub nesting: Option<NestingPermissions>,671 pub nesting: Option<NestingPermissions>,469}672}470673471impl CollectionPermissions {674impl CollectionPermissions {675 /// Get effective value for [`access`](self.access).472 pub fn access(&self) -> AccessMode {676 pub fn access(&self) -> AccessMode {473 self.access.unwrap_or(AccessMode::Normal)677 self.access.unwrap_or(AccessMode::Normal)474 }678 }679680 /// Get effective value for [`mint_mode`](self.mint_mode).475 pub fn mint_mode(&self) -> bool {681 pub fn mint_mode(&self) -> bool {476 self.mint_mode.unwrap_or(false)682 self.mint_mode.unwrap_or(false)477 }683 }684685 /// Get effective value for [`nesting`](self.nesting).478 pub fn nesting(&self) -> &NestingPermissions {686 pub fn nesting(&self) -> &NestingPermissions {479 static DEFAULT: NestingPermissions = NestingPermissions {687 static DEFAULT: NestingPermissions = NestingPermissions {480 token_owner: false,688 token_owner: false,487 }695 }488}696}489697698/// Inner set for collections allowed to nest.490type OwnerRestrictedSetInner = BoundedBTreeSet<CollectionId, ConstU32<16>>;699type OwnerRestrictedSetInner = BoundedBTreeSet<CollectionId, ConstU32<16>>;491700701/// Wraper for collections set allowing nest.492#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]702#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]493#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]703#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]494#[derivative(Debug)]704#[derivative(Debug)]499);709);710500impl OwnerRestrictedSet {711impl OwnerRestrictedSet {712 /// Create new set.501 pub fn new() -> Self {713 pub fn new() -> Self {502 Self(Default::default())714 Self(Default::default())503 }715 }519#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]731#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]520#[derivative(Debug)]732#[derivative(Debug)]521pub struct NestingPermissions {733pub struct NestingPermissions {522 /// Owner of token can nest tokens under it734 /// Owner of token can nest tokens under it.523 pub token_owner: bool,735 pub token_owner: bool,524 /// Admin of token collection can nest tokens under token736 /// Admin of token collection can nest tokens under token.525 pub collection_admin: bool,737 pub collection_admin: bool,526 /// If set - only tokens from specified collections can be nested738 /// If set - only tokens from specified collections can be nested.527 pub restricted: Option<OwnerRestrictedSet>,739 pub restricted: Option<OwnerRestrictedSet>,528740529 #[cfg(feature = "runtime-benchmarks")]741 #[cfg(feature = "runtime-benchmarks")]530 /// Anyone can nest tokens, mutually exclusive with `token_owner`, `admin`742 /// Anyone can nest tokens, mutually exclusive with `token_owner`, `admin`.531 pub permissive: bool,743 pub permissive: bool,532}744}533745534/// Enum denominating how often can sponsoring occur if it is enabled.746/// Enum denominating how often can sponsoring occur if it is enabled.747///748/// Used for [`collection limits`](CollectionLimits).535#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]749#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]536#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]750#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]537pub enum SponsoringRateLimit {751pub enum SponsoringRateLimit {549 /// Key-value pairs used to describe the token as metadata763 /// Key-value pairs used to describe the token as metadata550 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]764 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]551 #[derivative(Debug(format_with = "bounded::vec_debug"))]765 #[derivative(Debug(format_with = "bounded::vec_debug"))]766 /// Properties that wil be assignet to created item.552 pub properties: CollectionPropertiesVec,767 pub properties: CollectionPropertiesVec,553}768}554769570 #[derivative(Debug(format_with = "bounded::vec_debug"))]785 #[derivative(Debug(format_with = "bounded::vec_debug"))]571 pub const_data: BoundedVec<u8, CustomDataLimit>,786 pub const_data: BoundedVec<u8, CustomDataLimit>,572787573 /// Number of pieces the RFT is split into788 /// Pieces of created token.574 pub pieces: u128,789 pub pieces: u128,575790576 /// Key-value pairs used to describe the token as metadata791 /// Key-value pairs used to describe the token as metadata579 pub properties: CollectionPropertiesVec,794 pub properties: CollectionPropertiesVec,580}795}581796797// TODO: remove this.582#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]798#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]583#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]799#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]584pub enum MetaUpdatePermission {800pub enum MetaUpdatePermission {588}804}589805590/// Enum holding data used for creation of all three item types.806/// Enum holding data used for creation of all three item types.807/// Unified data for create item.591#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]808#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]592#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]809#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]593pub enum CreateItemData {810pub enum CreateItemData {811 /// Data for create NFT.594 NFT(CreateNftData),812 NFT(CreateNftData),813 /// Data for create Fungible item.595 Fungible(CreateFungibleData),814 Fungible(CreateFungibleData),815 /// Data for create ReFungible item.596 ReFungible(CreateReFungibleData),816 ReFungible(CreateReFungibleData),597}817}598818599/// Explicit NFT creation data with meta parameters.819/// Extended data for create NFT.600#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]820#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]601#[derivative(Debug)]821#[derivative(Debug)]602pub struct CreateNftExData<CrossAccountId> {822pub struct CreateNftExData<CrossAccountId> {823 /// Properties that wil be assignet to created item.603 #[derivative(Debug(format_with = "bounded::vec_debug"))]824 #[derivative(Debug(format_with = "bounded::vec_debug"))]604 pub properties: CollectionPropertiesVec,825 pub properties: CollectionPropertiesVec,826827 /// Owner of creating item.605 pub owner: CrossAccountId,828 pub owner: CrossAccountId,606}829}607830608/// Explicit RFT creation data with meta parameters.831/// Extended data for create ReFungible item.609#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]832#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]610#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]833#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]611pub struct CreateRefungibleExData<CrossAccountId> {834pub struct CreateRefungibleExData<CrossAccountId> {835 /// Custom data stored in token.612 #[derivative(Debug(format_with = "bounded::vec_debug"))]836 #[derivative(Debug(format_with = "bounded::vec_debug"))]613 pub const_data: BoundedVec<u8, CustomDataLimit>,837 pub const_data: BoundedVec<u8, CustomDataLimit>,838839 /// Users who will be assigned the specified number of token parts.614 #[derivative(Debug(format_with = "bounded::map_debug"))]840 #[derivative(Debug(format_with = "bounded::map_debug"))]615 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,841 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,616 #[derivative(Debug(format_with = "bounded::vec_debug"))]842 #[derivative(Debug(format_with = "bounded::vec_debug"))]617 pub properties: CollectionPropertiesVec,843 pub properties: CollectionPropertiesVec,618}844}619845620/// Explicit item creation data with meta parameters, namely the owner.846/// Unified extended data for creating item.621#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]847#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]622#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]848#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]623pub enum CreateItemExData<CrossAccountId> {849pub enum CreateItemExData<CrossAccountId> {850 /// Extended data for create NFT.624 NFT(851 NFT(625 #[derivative(Debug(format_with = "bounded::vec_debug"))]852 #[derivative(Debug(format_with = "bounded::vec_debug"))]626 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,853 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,627 ),854 ),855856 /// Extended data for create Fungible item.628 Fungible(857 Fungible(629 #[derivative(Debug(format_with = "bounded::map_debug"))]858 #[derivative(Debug(format_with = "bounded::map_debug"))]630 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,859 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,631 ),860 ),861862 /// Extended data for create ReFungible item in case of632 /// Many tokens, each may have only one owner863 /// many tokens, each may have only one owner633 RefungibleMultipleItems(864 RefungibleMultipleItems(634 #[derivative(Debug(format_with = "bounded::vec_debug"))]865 #[derivative(Debug(format_with = "bounded::vec_debug"))]635 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,866 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,636 ),867 ),868869 /// Extended data for create ReFungible item in case of637 /// Single token, which may have many owners870 /// single token, which may have many owners638 RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),871 RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),639}872}640873641impl CreateItemData {874impl CreateItemData {875 /// Get size of custom data.642 pub fn data_size(&self) -> usize {876 pub fn data_size(&self) -> usize {643 match self {877 match self {644 CreateItemData::ReFungible(data) => data.const_data.len(),878 CreateItemData::ReFungible(data) => data.const_data.len(),670#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]904#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]671// todo possibly rename to be used generally as an address pair905// todo possibly rename to be used generally as an address pair672pub struct TokenChild {906pub struct TokenChild {907 /// Token id.673 pub token: TokenId,908 pub token: TokenId,909910 /// Collection id.674 pub collection: CollectionId,911 pub collection: CollectionId,675}912}676913914/// Collection statistics.677#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]915#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]678#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]916#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]679pub struct CollectionStats {917pub struct CollectionStats {918 /// Number of created items.680 pub created: u32,919 pub created: u32,920921 /// Number of burned items.681 pub destroyed: u32,922 pub destroyed: u32,923924 /// Number of current items.682 pub alive: u32,925 pub alive: u32,683}926}684927928/// This type works like [`PhantomData`] but supports generating _scale-info_ descriptions to generate node metadata.685#[derive(Encode, Decode, Clone, Debug)]929#[derive(Encode, Decode, Clone, Debug)]686#[cfg_attr(feature = "std", derive(PartialEq))]930#[cfg_attr(feature = "std", derive(PartialEq))]687pub struct PhantomType<T>(core::marker::PhantomData<T>);931pub struct PhantomType<T>(core::marker::PhantomData<T>);707 }951 }708}952}709953954/// Bounded vector of bytes.710pub type BoundedBytes<S> = BoundedVec<u8, S>;955pub type BoundedBytes<S> = BoundedVec<u8, S>;711956957/// Extra properties for external collections.712pub type AuxPropertyValue = BoundedBytes<ConstU32<MAX_AUX_PROPERTY_VALUE_LENGTH>>;958pub type AuxPropertyValue = BoundedBytes<ConstU32<MAX_AUX_PROPERTY_VALUE_LENGTH>>;713959960/// Property key.714pub type PropertyKey = BoundedBytes<ConstU32<MAX_PROPERTY_KEY_LENGTH>>;961pub type PropertyKey = BoundedBytes<ConstU32<MAX_PROPERTY_KEY_LENGTH>>;962963/// Property value.715pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;964pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;716965966/// Property permission.717#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]967#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]718#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]968#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]719pub struct PropertyPermission {969pub struct PropertyPermission {970 /// Permission to change the property and property permission.971 ///972 /// If it **false** then you can not change corresponding property even if [`collection_admin`] and [`token_owner`] are **true**.720 pub mutable: bool,973 pub mutable: bool,974975 /// Change permission for the collection administrator.721 pub collection_admin: bool,976 pub collection_admin: bool,977978 /// Permission to change the property for the owner of the token.722 pub token_owner: bool,979 pub token_owner: bool,723}980}724981725impl PropertyPermission {982impl PropertyPermission {983 /// Creates mutable property permission but changes restricted for collection admin and token owner.726 pub fn none() -> Self {984 pub fn none() -> Self {727 Self {985 Self {728 mutable: true,986 mutable: true,732 }990 }733}991}734992993/// Property is simpl key-value record.735#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]994#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]736#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]995#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]737pub struct Property {996pub struct Property {997 /// Property key.738 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]998 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]739 pub key: PropertyKey,999 pub key: PropertyKey,74010001001 /// Property value.741 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1002 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]742 pub value: PropertyValue,1003 pub value: PropertyValue,743}1004}748 }1009 }749}1010}75010111012/// Record for proprty key permission.751#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]1013#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]752#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1014#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]753pub struct PropertyKeyPermission {1015pub struct PropertyKeyPermission {1016 /// Key.754 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1017 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]755 pub key: PropertyKey,1018 pub key: PropertyKey,75610191020 /// Permission.757 pub permission: PropertyPermission,1021 pub permission: PropertyPermission,758}1022}7591023763 }1027 }764}1028}76510291030/// Errors for properties actions.766#[derive(Debug)]1031#[derive(Debug)]767pub enum PropertiesError {1032pub enum PropertiesError {1033 /// The space allocated for properties has run out.1034 ///1035 /// * Limit for colection - [`MAX_COLLECTION_PROPERTIES_SIZE`].1036 /// * Limit for token - [`MAX_TOKEN_PROPERTIES_SIZE`].768 NoSpaceForProperty,1037 NoSpaceForProperty,10381039 /// The property limit has been reached.1040 ///1041 /// * Limit - [`MAX_PROPERTIES_PER_ITEM`].769 PropertyLimitReached,1042 PropertyLimitReached,10431044 /// Property key contains not allowed character.770 InvalidCharacterInPropertyKey,1045 InvalidCharacterInPropertyKey,10461047 /// Property key length is too long.1048 ///1049 /// * Limit - [`MAX_PROPERTY_KEY_LENGTH`].771 PropertyKeyIsTooLong,1050 PropertyKeyIsTooLong,10511052 /// Property key is empty.772 EmptyPropertyKey,1053 EmptyPropertyKey,773}1054}77410551056/// Marker for scope of property.1057///1058/// Scoped property can't be changed by user. Used for external collections.775#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Clone, Copy)]1059#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Clone, Copy)]776pub enum PropertyScope {1060pub enum PropertyScope {777 None,1061 None,778 Rmrk,1062 Rmrk,779}1063}7801064781impl PropertyScope {1065impl PropertyScope {1066 /// Apply scope to property key.782 pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {1067 pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {783 let scope_str: &[u8] = match self {1068 let scope_str: &[u8] = match self {784 Self::None => return Ok(key),1069 Self::None => return Ok(key),792 }1077 }793}1078}79410791080/// Trait for operate with properties.795pub trait TrySetProperty: Sized {1081pub trait TrySetProperty: Sized {796 type Value;1082 type Value;79710831084 /// Try to set property with scope.798 fn try_scoped_set(1085 fn try_scoped_set(799 &mut self,1086 &mut self,800 scope: PropertyScope,1087 scope: PropertyScope,801 key: PropertyKey,1088 key: PropertyKey,802 value: Self::Value,1089 value: Self::Value,803 ) -> Result<(), PropertiesError>;1090 ) -> Result<(), PropertiesError>;80410911092 /// Try to set property with scope from iterator.805 fn try_scoped_set_from_iter<I, KV>(1093 fn try_scoped_set_from_iter<I, KV>(806 &mut self,1094 &mut self,807 scope: PropertyScope,1095 scope: PropertyScope,819 Ok(())1107 Ok(())820 }1108 }82111091110 /// Try to set property.822 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {1111 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {823 self.try_scoped_set(PropertyScope::None, key, value)1112 self.try_scoped_set(PropertyScope::None, key, value)824 }1113 }82511141115 /// Try to set property from iterator.826 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>1116 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>827 where1117 where828 I: Iterator<Item = KV>,1118 I: Iterator<Item = KV>,832 }1122 }833}1123}83411241125/// Wrapped map for storing properties.835#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]1126#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]836#[derivative(Default(bound = ""))]1127#[derivative(Default(bound = ""))]837pub struct PropertiesMap<Value>(1128pub struct PropertiesMap<Value>(838 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,1129 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,839);1130);8401131841impl<Value> PropertiesMap<Value> {1132impl<Value> PropertiesMap<Value> {1133 /// Create new property map.842 pub fn new() -> Self {1134 pub fn new() -> Self {843 Self(BoundedBTreeMap::new())1135 Self(BoundedBTreeMap::new())844 }1136 }84511371138 /// Remove property from map.846 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {1139 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {847 Self::check_property_key(key)?;1140 Self::check_property_key(key)?;8481141849 Ok(self.0.remove(key))1142 Ok(self.0.remove(key))850 }1143 }85111441145 /// Get property with appropriate key from map.852 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {1146 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {853 self.0.get(key)1147 self.0.get(key)854 }1148 }85511491150 /// Check if map contains key.856 pub fn contains_key(&self, key: &PropertyKey) -> bool {1151 pub fn contains_key(&self, key: &PropertyKey) -> bool {857 self.0.contains_key(key)1152 self.0.contains_key(key)858 }1153 }85911541155 /// Check if map contains key with key validation.860 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {1156 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {861 if key.is_empty() {1157 if key.is_empty() {862 return Err(PropertiesError::EmptyPropertyKey);1158 return Err(PropertiesError::EmptyPropertyKey);909 }1205 }910}1206}91112071208/// Alias for property permissions map.912pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;1209pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;91312101211/// Wrapper for properties map with consumed space control.914#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]1212#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]915pub struct Properties {1213pub struct Properties {916 map: PropertiesMap<PropertyValue>,1214 map: PropertiesMap<PropertyValue>,919}1217}9201218921impl Properties {1219impl Properties {1220 /// Create new properies container.922 pub fn new(space_limit: u32) -> Self {1221 pub fn new(space_limit: u32) -> Self {923 Self {1222 Self {924 map: PropertiesMap::new(),1223 map: PropertiesMap::new(),927 }1226 }928 }1227 }92912281229 /// Remove propery with appropiate key.930 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {1230 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {931 let value = self.map.remove(key)?;1231 let value = self.map.remove(key)?;9321232938 Ok(value)1238 Ok(value)939 }1239 }94012401241 /// Get property with appropriate key.941 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {1242 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {942 self.map.get(key)1243 self.map.get(key)943 }1244 }977 }1278 }978}1279}97912801281/// Utility struct for using in `StorageMap`.980pub struct CollectionProperties;1282pub struct CollectionProperties;9811283982impl Get<Properties> for CollectionProperties {1284impl Get<Properties> for CollectionProperties {985 }1287 }986}1288}98712891290/// Utility struct for using in `StorageMap`.988pub struct TokenProperties;1291pub struct TokenProperties;9891292990impl Get<Properties> for TokenProperties {1293impl Get<Properties> for TokenProperties {primitives/data-structs/src/mapping.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//! This module contains mapping between different addresses.181use core::marker::PhantomData;19use core::marker::PhantomData;2205use crate::{CollectionId, TokenId};23use crate::{CollectionId, TokenId};6use pallet_evm::account::CrossAccountId;24use pallet_evm::account::CrossAccountId;72526/// Trait for mapping between token id and some `Address`.8pub trait TokenAddressMapping<Address> {27pub trait TokenAddressMapping<Address> {28 /// Map token id to `Address`.9 fn token_to_address(collection: CollectionId, token: TokenId) -> Address;29 fn token_to_address(collection: CollectionId, token: TokenId) -> Address;3031 /// Map `Address` to token id.10 fn address_to_token(address: &Address) -> Option<(CollectionId, TokenId)>;32 fn address_to_token(address: &Address) -> Option<(CollectionId, TokenId)>;3334 /// Check is address for token.11 fn is_token_address(address: &Address) -> bool;35 fn is_token_address(address: &Address) -> bool;12}36}133738/// Unit struct for mapping token id to/from *Evm address* represented by [`H160`].14pub struct EvmTokenAddressMapping;39pub struct EvmTokenAddressMapping;154016/// 0xf8238ccfff8ed887463fd5e00000000100000002 - collection 1, token 241/// 0xf8238ccfff8ed887463fd5e00000000100000002 - collection 1, token 246 }71 }47}72}487374/// Unit struct for mapping token id to/from [`CrossAccountId`].49pub struct CrossTokenAddressMapping<A>(PhantomData<A>);75pub struct CrossTokenAddressMapping<A>(PhantomData<A>);507651impl<A, C: CrossAccountId<A>> TokenAddressMapping<C> for CrossTokenAddressMapping<A> {77impl<A, C: CrossAccountId<A>> TokenAddressMapping<C> for CrossTokenAddressMapping<A> {primitives/rpc/src/lib.rsdiffbeforeafterboth282829sp_api::decl_runtime_apis! {29sp_api::decl_runtime_apis! {30 #[api_version(2)]30 #[api_version(2)]31 /// Trait for generate rpc.31 pub trait UniqueApi<CrossAccountId, AccountId> where32 pub trait UniqueApi<CrossAccountId, AccountId> where32 AccountId: Decode,33 AccountId: Decode,33 CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,34 CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,34 {35 {35 #[changed_in(2)]36 #[changed_in(2)]36 fn token_owner(collection: CollectionId, token: TokenId) -> Result<CrossAccountId>;37 fn token_owner(collection: CollectionId, token: TokenId) -> Result<CrossAccountId>;373839 /// Get number of tokens in collection owned by account.38 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>>;40 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>>;4142 /// Number of existing tokens in collection.39 fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>>;43 fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>>;4445 /// Check token exist.40 fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool>;46 fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool>;414748 /// Get token owner.42 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;49 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;5051 /// Get real owner of nested token.43 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;52 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;5354 /// Get nested tokens for the specified item.44 fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>>;55 fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>>;455657 /// Get collection properties.46 fn collection_properties(collection: CollectionId, properties: Option<Vec<Vec<u8>>>) -> Result<Vec<Property>>;58 fn collection_properties(collection: CollectionId, properties: Option<Vec<Vec<u8>>>) -> Result<Vec<Property>>;475960 /// Get token properties.48 fn token_properties(61 fn token_properties(49 collection: CollectionId,62 collection: CollectionId,50 token_id: TokenId,63 token_id: TokenId,51 properties: Option<Vec<Vec<u8>>>64 properties: Option<Vec<Vec<u8>>>52 ) -> Result<Vec<Property>>;65 ) -> Result<Vec<Property>>;536667 /// Get permissions for token properties.54 fn property_permissions(68 fn property_permissions(55 collection: CollectionId,69 collection: CollectionId,56 properties: Option<Vec<Vec<u8>>>70 properties: Option<Vec<Vec<u8>>>57 ) -> Result<Vec<PropertyKeyPermission>>;71 ) -> Result<Vec<PropertyKeyPermission>>;587273 /// Get token data.59 fn token_data(74 fn token_data(60 collection: CollectionId,75 collection: CollectionId,61 token_id: TokenId,76 token_id: TokenId,62 keys: Option<Vec<Vec<u8>>>77 keys: Option<Vec<Vec<u8>>>63 ) -> Result<TokenData<CrossAccountId>>;78 ) -> Result<TokenData<CrossAccountId>>;647980 /// Total number of tokens in collection.65 fn total_supply(collection: CollectionId) -> Result<u32>;81 fn total_supply(collection: CollectionId) -> Result<u32>;8283 /// Get account balance for collection (sum of tokens pieces).66 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32>;84 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32>;8586 /// Get account balance for specified token.67 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128>;87 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128>;8889 /// Amount of token pieces allowed to spend from granded account.68 fn allowance(90 fn allowance(69 collection: CollectionId,91 collection: CollectionId,70 sender: CrossAccountId,92 sender: CrossAccountId,71 spender: CrossAccountId,93 spender: CrossAccountId,72 token: TokenId,94 token: TokenId,73 ) -> Result<u128>;95 ) -> Result<u128>;749697 /// Get list of collection admins.75 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>>;98 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>>;99100 /// Get list of users that allowet to mint tikens in collection.76 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>>;101 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>>;102103 /// Check that user is in allowed list (see [`allowlist`]).77 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool>;104 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool>;105106 /// Last minted token id.78 fn last_token_id(collection: CollectionId) -> Result<TokenId>;107 fn last_token_id(collection: CollectionId) -> Result<TokenId>;108109 /// Get collection by id.79 fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>>;110 fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>>;111112 /// Get collection stats.80 fn collection_stats() -> Result<CollectionStats>;113 fn collection_stats() -> Result<CollectionStats>;114115 /// Get the number of blocks through which sponsorship will be available.81 fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>>;116 fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>>;117118 /// Get effective colletion limits.82 fn effective_collection_limits(collection_id: CollectionId) -> Result<Option<CollectionLimits>>;119 fn effective_collection_limits(collection_id: CollectionId) -> Result<Option<CollectionLimits>>;120121 /// Get total pieces of token.83 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Result<Option<u128>>;122 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Result<Option<u128>>;84 fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec<CrossAccountId>>;123 fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec<CrossAccountId>>;85 }124 }