difftreelog
added consts to `Unique` pallet
in: master
6 files changed
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -86,6 +86,8 @@
use sp_std::{vec, vec::Vec};
use up_data_structs::{
MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
+ MAX_PROPERTIES_PER_ITEM, MAX_PROPERTY_KEY_LENGTH, MAX_PROPERTY_VALUE_LENGTH,
+ MAX_COLLECTION_PROPERTIES_SIZE, COLLECTION_ADMINS_LIMIT, MAX_TOKEN_PROPERTIES_SIZE,
CreateItemData, CollectionLimits, CollectionPermissions, CollectionId, CollectionMode, TokenId,
SponsorshipState, CreateCollectionData, CreateItemExData, budget, Property, PropertyKey,
PropertyKeyPermission,
@@ -277,6 +279,46 @@
{
type Error = Error<T>;
+ #[doc = "Maximum number of levels of depth in the token nesting tree."]
+ const NESTING_BUDGET: u32 = NESTING_BUDGET;
+
+ #[doc = "Maximum length for collection name."]
+ const MAX_COLLECTION_NAME_LENGTH: u32 = MAX_COLLECTION_NAME_LENGTH;
+
+ #[doc = "Maximum length for collection description."]
+ const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = MAX_COLLECTION_DESCRIPTION_LENGTH;
+
+ #[doc = "Maximal token prefix length."]
+ const MAX_TOKEN_PREFIX_LENGTH: u32 = MAX_TOKEN_PREFIX_LENGTH;
+
+ #[doc = "Maximum admins per collection."]
+ const COLLECTION_ADMINS_LIMIT: u32 = COLLECTION_ADMINS_LIMIT;
+
+ #[doc = "Maximal lenght of property key."]
+ const MAX_PROPERTY_KEY_LENGTH: u32 = MAX_PROPERTY_KEY_LENGTH;
+
+ #[doc = "Maximal lenght of property value."]
+ const MAX_PROPERTY_VALUE_LENGTH: u32 = MAX_PROPERTY_VALUE_LENGTH;
+
+ #[doc = "Maximum properties that can be assigned to token."]
+ const MAX_PROPERTIES_PER_ITEM: u32 = MAX_PROPERTIES_PER_ITEM;
+
+ #[doc = "Maximum size for all collection properties."]
+ const MAX_COLLECTION_PROPERTIES_SIZE: u32 = MAX_COLLECTION_PROPERTIES_SIZE;
+
+ #[doc = "Maximum size for all token properties."]
+ const MAX_TOKEN_PROPERTIES_SIZE: u32 = MAX_TOKEN_PROPERTIES_SIZE;
+
+ #[doc = "Default NFT collection limit."]
+ const NFT_DEFAULT_COLLECTION_LIMITS: CollectionLimits = CollectionLimits::with_default_limits(CollectionMode::NFT);
+
+ #[doc = "Default RFT collection limit."]
+ const RFT_DEFAULT_COLLECTION_LIMITS: CollectionLimits = CollectionLimits::with_default_limits(CollectionMode::ReFungible);
+
+ #[doc = "Default FT collection limit."]
+ const FT_DEFAULT_COLLECTION_LIMITS: CollectionLimits = CollectionLimits::with_default_limits(CollectionMode::Fungible(0));
+
+
pub fn deposit_event() = default;
fn on_initialize(_now: T::BlockNumber) -> Weight {
primitives/data-structs/CHANGELOG.mddiffbeforeafterboth--- a/primitives/data-structs/CHANGELOG.md
+++ b/primitives/data-structs/CHANGELOG.md
@@ -3,6 +3,7 @@
All notable changes to this project will be documented in this file.
<!-- bureaucrate goes here -->
+
## [v0.2.2] 2022-08-16
### Other changes
@@ -28,12 +29,19 @@
multiple users into `RefungibleMultipleItems` call.
## [v0.2.0] - 2022-08-01
+
### Deprecated
+
- `CreateReFungibleData::const_data`
## [v0.1.2] - 2022-07-25
+
### Added
+
- Type aliases `CollectionName`, `CollectionDescription`, `CollectionTokenPrefix`
+
## [v0.1.1] - 2022-07-22
+
### Added
-- Аields with properties to `CreateReFungibleData` and `CreateRefungibleExData`.
\ No newline at end of file
+
+- Аields with properties to `CreateReFungibleData` and `CreateRefungibleExData`.
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//! # Primitives crate.18//!19//! This crate contains types, traits and constants.2021#![cfg_attr(not(feature = "std"), no_std)]2223use core::{24 convert::{TryFrom, TryInto},25 fmt,26};27use frame_support::{28 storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},29 traits::Get,30 parameter_types,31};3233#[cfg(feature = "serde")]34use serde::{Serialize, Deserialize};3536use sp_core::U256;37use sp_runtime::{ArithmeticError, sp_std::prelude::Vec, Permill};38use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};39use bondrewd::Bitfields;40use frame_support::{BoundedVec, traits::ConstU32};41use derivative::Derivative;42use scale_info::TypeInfo;4344// RMRK45use rmrk_traits::{46 CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme, ThemeProperty,47 ResourceTypes, BasicResource, ComposableResource, SlotResource, EquippableList,48};49pub use rmrk_traits::{50 primitives::{51 CollectionId as RmrkCollectionId, NftId as RmrkNftId, BaseId as RmrkBaseId,52 SlotId as RmrkSlotId, PartId as RmrkPartId, ResourceId as RmrkResourceId,53 },54 NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,55 FixedPart as RmrkFixedPart, SlotPart as RmrkSlotPart,56};5758mod bondrewd_codec;59mod bounded;60pub mod budget;61pub mod mapping;62mod migration;6364/// Maximum of decimal points.65pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;6667/// Maximum pieces for refungible token.68pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;69pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;7071/// Maximum tokens for user.72pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {73 100_00074} else {75 1076};7778/// Maximum for collections can be created.79pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {80 100_00081} else {82 1083};8485/// Maximum for various custom data of token.86pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {87 204888} else {89 1090};9192/// Maximum admins per collection.93pub const COLLECTION_ADMINS_LIMIT: u32 = 5;9495/// Maximum tokens per collection.96pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;9798/// Maximum tokens per account.99pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {100 1_000_000101} else {102 10103};104105/// Default timeout for transfer sponsoring NFT item.106pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;107/// Default timeout for transfer sponsoring fungible item.108pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;109/// Default timeout for transfer sponsoring refungible item.110pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;111112/// Default timeout for sponsored approving.113pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;114115// Schema limits116pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;117pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;118pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;119120// TODO: not used. Delete?121pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;122123/// Maximum length for collection name.124pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;125126/// Maximum length for collection description.127pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;128129/// Maximal token prefix length.130pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;131132/// Maximal lenght of property key.133pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;134135/// Maximal lenght of property value.136pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;137138/// Maximum properties that can be assigned to token.139pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;140141/// Maximal lenght of extended property value.142pub const MAX_AUX_PROPERTY_VALUE_LENGTH: u32 = 2048;143144/// Maximum size for all collection properties.145pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;146147/// Maximum size for all token properties.148pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;149150/// How much items can be created per single151/// create_many call.152pub const MAX_ITEMS_PER_BATCH: u32 = 200;153154/// Used for limit bounded types of token custom data.155pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;156157/// Collection id.158#[derive(159 Encode,160 Decode,161 PartialEq,162 Eq,163 PartialOrd,164 Ord,165 Clone,166 Copy,167 Debug,168 Default,169 TypeInfo,170 MaxEncodedLen,171)]172#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]173pub struct CollectionId(pub u32);174impl EncodeLike<u32> for CollectionId {}175impl EncodeLike<CollectionId> for u32 {}176177/// Token id.178#[derive(179 Encode,180 Decode,181 PartialEq,182 Eq,183 PartialOrd,184 Ord,185 Clone,186 Copy,187 Debug,188 Default,189 TypeInfo,190 MaxEncodedLen,191)]192#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]193pub struct TokenId(pub u32);194impl EncodeLike<u32> for TokenId {}195impl EncodeLike<TokenId> for u32 {}196197impl TokenId {198 /// Try to get next token id.199 ///200 /// If next id cause overflow, then [`ArithmeticError::Overflow`] returned.201 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {202 self.0203 .checked_add(1)204 .ok_or(ArithmeticError::Overflow)205 .map(Self)206 }207}208209impl From<TokenId> for U256 {210 fn from(t: TokenId) -> Self {211 t.0.into()212 }213}214215impl TryFrom<U256> for TokenId {216 type Error = &'static str;217218 fn try_from(value: U256) -> Result<Self, Self::Error> {219 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))220 }221}222223/// Token data.224#[struct_versioning::versioned(version = 2, upper)]225#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]226#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]227pub struct TokenData<CrossAccountId> {228 /// Properties of token.229 pub properties: Vec<Property>,230231 /// Token owner.232 pub owner: Option<CrossAccountId>,233234 /// Token pieces.235 #[version(2.., upper(0))]236 pub pieces: u128,237}238239// TODO: unused type240pub struct OverflowError;241impl From<OverflowError> for &'static str {242 fn from(_: OverflowError) -> Self {243 "overflow occured"244 }245}246247/// Alias for decimal points type.248pub type DecimalPoints = u8;249250/// Collection mode.251///252/// Collection can represent various types of tokens.253/// Each collection can contain only one type of tokens at a time.254/// This type helps to understand which tokens the collection contains.255#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]256#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]257pub enum CollectionMode {258 /// Non fungible tokens.259 NFT,260 /// Fungible tokens.261 Fungible(DecimalPoints),262 /// Refungible tokens.263 ReFungible,264}265266impl CollectionMode {267 /// Get collection mod as number.268 pub fn id(&self) -> u8 {269 match self {270 CollectionMode::NFT => 1,271 CollectionMode::Fungible(_) => 2,272 CollectionMode::ReFungible => 3,273 }274 }275}276277// TODO: unused trait278pub trait SponsoringResolve<AccountId, Call> {279 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;280}281282/// Access mode for some token operations.283#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]284#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]285pub enum AccessMode {286 /// Access grant for owner and admins. Used as default.287 Normal,288 /// Like a [`Normal`](AccessMode::Normal) but also users in allow list.289 AllowList,290}291impl Default for AccessMode {292 fn default() -> Self {293 Self::Normal294 }295}296297// TODO: remove in future.298#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]299#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]300pub enum SchemaVersion {301 ImageURL,302 Unique,303}304impl Default for SchemaVersion {305 fn default() -> Self {306 Self::ImageURL307 }308}309310// TODO: unused type311#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]312#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]313pub struct Ownership<AccountId> {314 pub owner: AccountId,315 pub fraction: u128,316}317318/// The state of collection sponsorship.319#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]320#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]321pub enum SponsorshipState<AccountId> {322 /// The fees are applied to the transaction sender.323 Disabled,324 /// The sponsor is under consideration. Until the sponsor gives his consent,325 /// the fee will still be charged to sender.326 Unconfirmed(AccountId),327 /// Transactions are sponsored by specified account.328 Confirmed(AccountId),329}330331impl<AccountId> SponsorshipState<AccountId> {332 /// Get a sponsor of the collection who has confirmed his status.333 pub fn sponsor(&self) -> Option<&AccountId> {334 match self {335 Self::Confirmed(sponsor) => Some(sponsor),336 _ => None,337 }338 }339340 /// Get a sponsor of the collection who has pending or confirmed status.341 pub fn pending_sponsor(&self) -> Option<&AccountId> {342 match self {343 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),344 _ => None,345 }346 }347348 /// Whether the sponsorship is confirmed.349 pub fn confirmed(&self) -> bool {350 matches!(self, Self::Confirmed(_))351 }352}353354impl<T> Default for SponsorshipState<T> {355 fn default() -> Self {356 Self::Disabled357 }358}359360pub type CollectionName = BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>;361pub type CollectionDescription = BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>;362pub type CollectionTokenPrefix = BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>;363364#[derive(Bitfields, Clone, Copy, PartialEq, Eq, Debug, Default)]365#[bondrewd(enforce_bytes = 1)]366pub struct CollectionFlags {367 /// Tokens in foreign collections can be transferred, but not burnt368 #[bondrewd(bits = "0..1")]369 pub foreign: bool,370 /// Supports ERC721Metadata371 #[bondrewd(bits = "1..2")]372 pub erc721metadata: bool,373 /// External collections can't be managed using `unique` api374 #[bondrewd(bits = "7..8")]375 pub external: bool,376377 #[bondrewd(reserve, bits = "2..7")]378 pub reserved: u8,379}380bondrewd_codec!(CollectionFlags);381382/// Base structure for represent collection.383///384/// Used to provide basic functionality for all types of collections.385///386/// #### Note387/// Collection parameters, used in storage (see [`RpcCollection`] for the RPC version).388#[struct_versioning::versioned(version = 2, upper)]389#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]390pub struct Collection<AccountId> {391 /// Collection owner account.392 pub owner: AccountId,393394 /// Collection mode.395 pub mode: CollectionMode,396397 /// Access mode.398 #[version(..2)]399 pub access: AccessMode,400401 /// Collection name.402 pub name: CollectionName,403404 /// Collection description.405 pub description: CollectionDescription,406407 /// Token prefix.408 pub token_prefix: CollectionTokenPrefix,409410 #[version(..2)]411 pub mint_mode: bool,412413 #[version(..2)]414 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,415416 #[version(..2)]417 pub schema_version: SchemaVersion,418419 /// The state of sponsorship of the collection.420 pub sponsorship: SponsorshipState<AccountId>,421422 /// Collection limits.423 pub limits: CollectionLimits,424425 /// Collection permissions.426 #[version(2.., upper(Default::default()))]427 pub permissions: CollectionPermissions,428429 #[version(2.., upper(Default::default()))]430 pub flags: CollectionFlags,431432 #[version(..2)]433 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,434435 #[version(..2)]436 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,437438 #[version(..2)]439 pub meta_update_permission: MetaUpdatePermission,440}441442#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]443#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]444pub struct RpcCollectionFlags {445 /// Is collection is foreign.446 pub foreign: bool,447 /// Collection supports ERC721Metadata.448 pub erc721metadata: bool,449}450451/// Collection parameters, used in RPC calls (see [`Collection`] for the storage version).452#[struct_versioning::versioned(version = 2, upper)]453#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]454#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]455pub struct RpcCollection<AccountId> {456 /// Collection owner account.457 pub owner: AccountId,458459 /// Collection mode.460 pub mode: CollectionMode,461462 /// Collection name.463 pub name: Vec<u16>,464465 /// Collection description.466 pub description: Vec<u16>,467468 /// Token prefix.469 pub token_prefix: Vec<u8>,470471 /// The state of sponsorship of the collection.472 pub sponsorship: SponsorshipState<AccountId>,473474 /// Collection limits.475 pub limits: CollectionLimits,476477 /// Collection permissions.478 pub permissions: CollectionPermissions,479480 /// Token property permissions.481 pub token_property_permissions: Vec<PropertyKeyPermission>,482483 /// Collection properties.484 pub properties: Vec<Property>,485486 /// Is collection read only.487 pub read_only: bool,488489 /// Extra collection flags490 #[version(2.., upper(RpcCollectionFlags {foreign: false, erc721metadata: false}))]491 pub flags: RpcCollectionFlags,492}493494/// Data used for create collection.495///496/// All fields are wrapped in [`Option`], where `None` means chain default.497#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]498#[derivative(Debug, Default(bound = ""))]499pub struct CreateCollectionData<AccountId> {500 /// Collection mode.501 #[derivative(Default(value = "CollectionMode::NFT"))]502 pub mode: CollectionMode,503504 /// Access mode.505 pub access: Option<AccessMode>,506507 /// Collection name.508 pub name: CollectionName,509510 /// Collection description.511 pub description: CollectionDescription,512513 /// Token prefix.514 pub token_prefix: CollectionTokenPrefix,515516 /// Pending collection sponsor.517 pub pending_sponsor: Option<AccountId>,518519 /// Collection limits.520 pub limits: Option<CollectionLimits>,521522 /// Collection permissions.523 pub permissions: Option<CollectionPermissions>,524525 /// Token property permissions.526 pub token_property_permissions: CollectionPropertiesPermissionsVec,527528 /// Collection properties.529 pub properties: CollectionPropertiesVec,530}531532/// Bounded vector of properties permissions. Max length is [`MAX_PROPERTIES_PER_ITEM`].533// TODO: maybe rename to PropertiesPermissionsVec534pub type CollectionPropertiesPermissionsVec =535 BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;536537/// Bounded vector of properties. Max length is [`MAX_PROPERTIES_PER_ITEM`].538pub type CollectionPropertiesVec = BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;539540/// Limits and restrictions of a collection.541///542/// All fields are wrapped in [`Option`], where `None` means chain default.543///544/// Update with `pallet_common::Pallet::clamp_limits`.545// IMPORTANT: When adding/removing fields from this struct - don't forget to also546#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]547#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]548// When adding/removing fields from this struct - don't forget to also update with `pallet_common::Pallet::clamp_limits`.549// TODO: move `pallet_common::Pallet::clamp_limits` into `impl CollectionLimits`.550// TODO: may be remove [`Option`] and **pub** from fields and create struct with default values.551pub struct CollectionLimits {552 /// How many tokens can a user have on one account.553 /// * Default - [`ACCOUNT_TOKEN_OWNERSHIP_LIMIT`].554 /// * Limit - [`MAX_TOKEN_OWNERSHIP`].555 pub account_token_ownership_limit: Option<u32>,556557 /// How many bytes of data are available for sponsorship.558 /// * Default - [`CUSTOM_DATA_LIMIT`].559 /// * Limit - [`CUSTOM_DATA_LIMIT`].560 pub sponsored_data_size: Option<u32>,561562 // FIXME should we delete this or repurpose it?563 /// Times in how many blocks we sponsor data.564 ///565 /// If is `Some(v)` then **setVariableMetadata** is sponsored if there is `v` block between transactions.566 ///567 /// * Default - [`SponsoringDisabled`](SponsoringRateLimit::SponsoringDisabled).568 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].569 ///570 /// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]571 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,572 /// Maximum amount of tokens inside the collection. Chain default: [`COLLECTION_TOKEN_LIMIT`]573574 /// How many tokens can be mined into this collection.575 ///576 /// * Default - [`COLLECTION_TOKEN_LIMIT`].577 /// * Limit - [`COLLECTION_TOKEN_LIMIT`].578 pub token_limit: Option<u32>,579580 /// Timeouts for transfer sponsoring.581 ///582 /// * Default583 /// - **Fungible** - [`FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`]584 /// - **NFT** - [`NFT_SPONSOR_TRANSFER_TIMEOUT`]585 /// - **Refungible** - [`REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`]586 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].587 pub sponsor_transfer_timeout: Option<u32>,588589 /// Timeout for sponsoring an approval in passed blocks.590 ///591 /// * Default - [`SPONSOR_APPROVE_TIMEOUT`].592 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].593 pub sponsor_approve_timeout: Option<u32>,594595 /// Whether the collection owner of the collection can send tokens (which belong to other users).596 ///597 /// * Default - **false**.598 pub owner_can_transfer: Option<bool>,599600 /// Can the collection owner burn other people's tokens.601 ///602 /// * Default - **true**.603 pub owner_can_destroy: Option<bool>,604605 /// Is it possible to send tokens from this collection between users.606 ///607 /// * Default - **true**.608 pub transfers_enabled: Option<bool>,609}610611impl CollectionLimits {612 /// Get effective value for [`account_token_ownership_limit`](self.account_token_ownership_limit).613 pub fn account_token_ownership_limit(&self) -> u32 {614 self.account_token_ownership_limit615 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)616 .min(MAX_TOKEN_OWNERSHIP)617 }618619 /// Get effective value for [`sponsored_data_size`](self.sponsored_data_size).620 pub fn sponsored_data_size(&self) -> u32 {621 self.sponsored_data_size622 .unwrap_or(CUSTOM_DATA_LIMIT)623 .min(CUSTOM_DATA_LIMIT)624 }625626 /// Get effective value for [`token_limit`](self.token_limit).627 pub fn token_limit(&self) -> u32 {628 self.token_limit629 .unwrap_or(COLLECTION_TOKEN_LIMIT)630 .min(COLLECTION_TOKEN_LIMIT)631 }632633 // TODO: may be replace u32 to mode?634 /// Get effective value for [`sponsor_transfer_timeout`](self.sponsor_transfer_timeout).635 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {636 self.sponsor_transfer_timeout637 .unwrap_or(default)638 .min(MAX_SPONSOR_TIMEOUT)639 }640641 /// Get effective value for [`sponsor_approve_timeout`](self.sponsor_approve_timeout).642 pub fn sponsor_approve_timeout(&self) -> u32 {643 self.sponsor_approve_timeout644 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)645 .min(MAX_SPONSOR_TIMEOUT)646 }647648 /// Get effective value for [`owner_can_transfer`](self.owner_can_transfer).649 pub fn owner_can_transfer(&self) -> bool {650 self.owner_can_transfer.unwrap_or(false)651 }652653 /// Get effective value for [`owner_can_transfer_instaled`](self.owner_can_transfer_instaled).654 pub fn owner_can_transfer_instaled(&self) -> bool {655 self.owner_can_transfer.is_some()656 }657658 /// Get effective value for [`owner_can_destroy`](self.owner_can_destroy).659 pub fn owner_can_destroy(&self) -> bool {660 self.owner_can_destroy.unwrap_or(true)661 }662663 /// Get effective value for [`transfers_enabled`](self.transfers_enabled).664 pub fn transfers_enabled(&self) -> bool {665 self.transfers_enabled.unwrap_or(true)666 }667668 /// Get effective value for [`sponsored_data_rate_limit`](self.sponsored_data_rate_limit).669 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {670 match self671 .sponsored_data_rate_limit672 .unwrap_or(SponsoringRateLimit::SponsoringDisabled)673 {674 SponsoringRateLimit::SponsoringDisabled => None,675 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),676 }677 }678}679680/// Permissions on certain operations within a collection.681///682/// Some fields are wrapped in [`Option`], where `None` means chain default.683///684/// Update with `pallet_common::Pallet::clamp_permissions`.685#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]686#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]687// When adding/removing fields from this struct - don't forget to also update `pallet_common::Pallet::clamp_permissions`.688// TODO: move `pallet_common::Pallet::clamp_permissions` into `impl CollectionPermissions`.689pub struct CollectionPermissions {690 /// Access mode.691 ///692 /// * Default - [`AccessMode::Normal`].693 pub access: Option<AccessMode>,694695 /// Minting allowance.696 ///697 /// * Default - **false**.698 pub mint_mode: Option<bool>,699700 /// Permissions for nesting.701 ///702 /// * Default703 /// - `token_owner` - **false**704 /// - `collection_admin` - **false**705 /// - `restricted` - **None**706 pub nesting: Option<NestingPermissions>,707}708709impl CollectionPermissions {710 /// Get effective value for [`access`](self.access).711 pub fn access(&self) -> AccessMode {712 self.access.unwrap_or(AccessMode::Normal)713 }714715 /// Get effective value for [`mint_mode`](self.mint_mode).716 pub fn mint_mode(&self) -> bool {717 self.mint_mode.unwrap_or(false)718 }719720 /// Get effective value for [`nesting`](self.nesting).721 pub fn nesting(&self) -> &NestingPermissions {722 static DEFAULT: NestingPermissions = NestingPermissions {723 token_owner: false,724 collection_admin: false,725 restricted: None,726 #[cfg(feature = "runtime-benchmarks")]727 permissive: false,728 };729 self.nesting.as_ref().unwrap_or(&DEFAULT)730 }731}732733/// Inner set for collections allowed to nest.734type OwnerRestrictedSetInner = BoundedBTreeSet<CollectionId, ConstU32<16>>;735736/// Wraper for collections set allowing nest.737#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]738#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]739#[derivative(Debug)]740pub struct OwnerRestrictedSet(741 #[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]742 #[derivative(Debug(format_with = "bounded::set_debug"))]743 pub OwnerRestrictedSetInner,744);745746impl OwnerRestrictedSet {747 /// Create new set.748 pub fn new() -> Self {749 Self(Default::default())750 }751}752impl core::ops::Deref for OwnerRestrictedSet {753 type Target = OwnerRestrictedSetInner;754 fn deref(&self) -> &Self::Target {755 &self.0756 }757}758impl core::ops::DerefMut for OwnerRestrictedSet {759 fn deref_mut(&mut self) -> &mut Self::Target {760 &mut self.0761 }762}763764/// Part of collection permissions, if set, defines who is able to nest tokens into other tokens.765#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]766#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]767#[derivative(Debug)]768pub struct NestingPermissions {769 /// Owner of token can nest tokens under it.770 pub token_owner: bool,771 /// Admin of token collection can nest tokens under token.772 pub collection_admin: bool,773 /// If set - only tokens from specified collections can be nested.774 pub restricted: Option<OwnerRestrictedSet>,775776 #[cfg(feature = "runtime-benchmarks")]777 /// Anyone can nest tokens, mutually exclusive with `token_owner`, `admin`.778 pub permissive: bool,779}780781/// Enum denominating how often can sponsoring occur if it is enabled.782///783/// Used for [`collection limits`](CollectionLimits).784#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]785#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]786pub enum SponsoringRateLimit {787 /// Sponsoring is disabled, and the collection sponsor will not pay for transactions788 SponsoringDisabled,789 /// Once per how many blocks can sponsorship of a transaction type occur790 Blocks(u32),791}792793/// Data used to describe an NFT at creation.794#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]795#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]796#[derivative(Debug)]797pub struct CreateNftData {798 /// Key-value pairs used to describe the token as metadata799 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]800 #[derivative(Debug(format_with = "bounded::vec_debug"))]801 /// Properties that wil be assignet to created item.802 pub properties: CollectionPropertiesVec,803}804805/// Data used to describe a Fungible token at creation.806#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]807#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]808pub struct CreateFungibleData {809 /// Number of fungible coins minted810 pub value: u128,811}812813/// Data used to describe a Refungible token at creation.814#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]815#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]816#[derivative(Debug)]817pub struct CreateReFungibleData {818 /// Number of pieces the RFT is split into819 pub pieces: u128,820821 /// Key-value pairs used to describe the token as metadata822 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]823 #[derivative(Debug(format_with = "bounded::vec_debug"))]824 pub properties: CollectionPropertiesVec,825}826827// TODO: remove this.828#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]829#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]830pub enum MetaUpdatePermission {831 ItemOwner,832 Admin,833 None,834}835836/// Enum holding data used for creation of all three item types.837/// Unified data for create item.838#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]839#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]840pub enum CreateItemData {841 /// Data for create NFT.842 NFT(CreateNftData),843 /// Data for create Fungible item.844 Fungible(CreateFungibleData),845 /// Data for create ReFungible item.846 ReFungible(CreateReFungibleData),847}848849/// Extended data for create NFT.850#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]851#[derivative(Debug)]852pub struct CreateNftExData<CrossAccountId> {853 /// Properties that wil be assignet to created item.854 #[derivative(Debug(format_with = "bounded::vec_debug"))]855 pub properties: CollectionPropertiesVec,856857 /// Owner of creating item.858 pub owner: CrossAccountId,859}860861/// Extended data for create ReFungible item.862#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]863#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]864pub struct CreateRefungibleExMultipleOwners<CrossAccountId> {865 #[derivative(Debug(format_with = "bounded::map_debug"))]866 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,867 #[derivative(Debug(format_with = "bounded::vec_debug"))]868 pub properties: CollectionPropertiesVec,869}870871/// Extended data for create ReFungible item.872#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]873#[derivative(Debug(bound = "CrossAccountId: fmt::Debug"))]874pub struct CreateRefungibleExSingleOwner<CrossAccountId> {875 pub user: CrossAccountId,876 pub pieces: u128,877 #[derivative(Debug(format_with = "bounded::vec_debug"))]878 pub properties: CollectionPropertiesVec,879}880881/// Unified extended data for creating item.882#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]883#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]884pub enum CreateItemExData<CrossAccountId> {885 /// Extended data for create NFT.886 NFT(887 #[derivative(Debug(format_with = "bounded::vec_debug"))]888 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,889 ),890891 /// Extended data for create Fungible item.892 Fungible(893 #[derivative(Debug(format_with = "bounded::map_debug"))]894 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,895 ),896897 /// Extended data for create ReFungible item in case of898 /// many tokens, each may have only one owner899 RefungibleMultipleItems(900 #[derivative(Debug(format_with = "bounded::vec_debug"))]901 BoundedVec<CreateRefungibleExSingleOwner<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,902 ),903904 /// Extended data for create ReFungible item in case of905 /// single token, which may have many owners906 RefungibleMultipleOwners(CreateRefungibleExMultipleOwners<CrossAccountId>),907}908909impl From<CreateNftData> for CreateItemData {910 fn from(item: CreateNftData) -> Self {911 CreateItemData::NFT(item)912 }913}914915impl From<CreateReFungibleData> for CreateItemData {916 fn from(item: CreateReFungibleData) -> Self {917 CreateItemData::ReFungible(item)918 }919}920921impl From<CreateFungibleData> for CreateItemData {922 fn from(item: CreateFungibleData) -> Self {923 CreateItemData::Fungible(item)924 }925}926927/// Token's address, dictated by its collection and token IDs.928#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]929#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]930// todo possibly rename to be used generally as an address pair931pub struct TokenChild {932 /// Token id.933 pub token: TokenId,934935 /// Collection id.936 pub collection: CollectionId,937}938939/// Collection statistics.940#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]941#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]942pub struct CollectionStats {943 /// Number of created items.944 pub created: u32,945946 /// Number of burned items.947 pub destroyed: u32,948949 /// Number of current items.950 pub alive: u32,951}952953/// This type works like [`PhantomData`] but supports generating _scale-info_ descriptions to generate node metadata.954#[derive(Encode, Decode, Clone, Debug)]955#[cfg_attr(feature = "std", derive(PartialEq))]956pub struct PhantomType<T>(core::marker::PhantomData<T>);957958impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {959 type Identity = PhantomType<T>;960961 fn type_info() -> scale_info::Type {962 use scale_info::{963 Type, Path,964 build::{FieldsBuilder, UnnamedFields},965 form::MetaForm,966 type_params,967 };968 Type::builder()969 .path(Path::new("up_data_structs", "PhantomType"))970 .type_params(type_params!(T))971 .composite(972 <FieldsBuilder<MetaForm, UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()),973 )974 }975}976impl<T> MaxEncodedLen for PhantomType<T> {977 fn max_encoded_len() -> usize {978 0979 }980}981982/// Bounded vector of bytes.983pub type BoundedBytes<S> = BoundedVec<u8, S>;984985/// Extra properties for external collections.986pub type AuxPropertyValue = BoundedBytes<ConstU32<MAX_AUX_PROPERTY_VALUE_LENGTH>>;987988/// Property key.989pub type PropertyKey = BoundedBytes<ConstU32<MAX_PROPERTY_KEY_LENGTH>>;990991/// Property value.992pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;993994/// Property permission.995#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]996#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]997pub struct PropertyPermission {998 /// Permission to change the property and property permission.999 ///1000 /// If it **false** then you can not change corresponding property even if [`collection_admin`] and [`token_owner`] are **true**.1001 pub mutable: bool,10021003 /// Change permission for the collection administrator.1004 pub collection_admin: bool,10051006 /// Permission to change the property for the owner of the token.1007 pub token_owner: bool,1008}10091010impl PropertyPermission {1011 /// Creates mutable property permission but changes restricted for collection admin and token owner.1012 pub fn none() -> Self {1013 Self {1014 mutable: true,1015 collection_admin: false,1016 token_owner: false,1017 }1018 }1019}10201021/// Property is simpl key-value record.1022#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]1023#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1024pub struct Property {1025 /// Property key.1026 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1027 pub key: PropertyKey,10281029 /// Property value.1030 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1031 pub value: PropertyValue,1032}10331034impl Into<(PropertyKey, PropertyValue)> for Property {1035 fn into(self) -> (PropertyKey, PropertyValue) {1036 (self.key, self.value)1037 }1038}10391040/// Record for proprty key permission.1041#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]1042#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1043pub struct PropertyKeyPermission {1044 /// Key.1045 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1046 pub key: PropertyKey,10471048 /// Permission.1049 pub permission: PropertyPermission,1050}10511052impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {1053 fn into(self) -> (PropertyKey, PropertyPermission) {1054 (self.key, self.permission)1055 }1056}10571058/// Errors for properties actions.1059#[derive(Debug)]1060pub enum PropertiesError {1061 /// The space allocated for properties has run out.1062 ///1063 /// * Limit for colection - [`MAX_COLLECTION_PROPERTIES_SIZE`].1064 /// * Limit for token - [`MAX_TOKEN_PROPERTIES_SIZE`].1065 NoSpaceForProperty,10661067 /// The property limit has been reached.1068 ///1069 /// * Limit - [`MAX_PROPERTIES_PER_ITEM`].1070 PropertyLimitReached,10711072 /// Property key contains not allowed character.1073 InvalidCharacterInPropertyKey,10741075 /// Property key length is too long.1076 ///1077 /// * Limit - [`MAX_PROPERTY_KEY_LENGTH`].1078 PropertyKeyIsTooLong,10791080 /// Property key is empty.1081 EmptyPropertyKey,1082}10831084/// Marker for scope of property.1085///1086/// Scoped property can't be changed by user. Used for external collections.1087#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Clone, Copy)]1088pub enum PropertyScope {1089 None,1090 Rmrk,1091}10921093impl PropertyScope {1094 /// Apply scope to property key.1095 pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {1096 let scope_str: &[u8] = match self {1097 Self::None => return Ok(key),1098 Self::Rmrk => b"rmrk",1099 };11001101 [scope_str, b":", key.as_slice()]1102 .concat()1103 .try_into()1104 .map_err(|_| PropertiesError::PropertyKeyIsTooLong)1105 }1106}11071108/// Trait for operate with properties.1109pub trait TrySetProperty: Sized {1110 type Value;11111112 /// Try to set property with scope.1113 fn try_scoped_set(1114 &mut self,1115 scope: PropertyScope,1116 key: PropertyKey,1117 value: Self::Value,1118 ) -> Result<(), PropertiesError>;11191120 /// Try to set property with scope from iterator.1121 fn try_scoped_set_from_iter<I, KV>(1122 &mut self,1123 scope: PropertyScope,1124 iter: I,1125 ) -> Result<(), PropertiesError>1126 where1127 I: Iterator<Item = KV>,1128 KV: Into<(PropertyKey, Self::Value)>,1129 {1130 for kv in iter {1131 let (key, value) = kv.into();1132 self.try_scoped_set(scope, key, value)?;1133 }11341135 Ok(())1136 }11371138 /// Try to set property.1139 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {1140 self.try_scoped_set(PropertyScope::None, key, value)1141 }11421143 /// Try to set property from iterator.1144 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>1145 where1146 I: Iterator<Item = KV>,1147 KV: Into<(PropertyKey, Self::Value)>,1148 {1149 self.try_scoped_set_from_iter(PropertyScope::None, iter)1150 }1151}11521153/// Wrapped map for storing properties.1154#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]1155#[derivative(Default(bound = ""))]1156pub struct PropertiesMap<Value>(1157 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,1158);11591160impl<Value> PropertiesMap<Value> {1161 /// Create new property map.1162 pub fn new() -> Self {1163 Self(BoundedBTreeMap::new())1164 }11651166 /// Remove property from map.1167 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {1168 Self::check_property_key(key)?;11691170 Ok(self.0.remove(key))1171 }11721173 /// Get property with appropriate key from map.1174 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {1175 self.0.get(key)1176 }11771178 /// Check if map contains key.1179 pub fn contains_key(&self, key: &PropertyKey) -> bool {1180 self.0.contains_key(key)1181 }11821183 /// Check if map contains key with key validation.1184 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {1185 if key.is_empty() {1186 return Err(PropertiesError::EmptyPropertyKey);1187 }11881189 for byte in key.as_slice().iter() {1190 let byte = *byte;11911192 if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' && byte != b'.' {1193 return Err(PropertiesError::InvalidCharacterInPropertyKey);1194 }1195 }11961197 Ok(())1198 }1199}12001201impl<Value> IntoIterator for PropertiesMap<Value> {1202 type Item = (PropertyKey, Value);1203 type IntoIter = <1204 BoundedBTreeMap<1205 PropertyKey,1206 Value,1207 ConstU32<MAX_PROPERTIES_PER_ITEM>1208 > as IntoIterator1209 >::IntoIter;12101211 fn into_iter(self) -> Self::IntoIter {1212 self.0.into_iter()1213 }1214}12151216impl<Value> TrySetProperty for PropertiesMap<Value> {1217 type Value = Value;12181219 fn try_scoped_set(1220 &mut self,1221 scope: PropertyScope,1222 key: PropertyKey,1223 value: Self::Value,1224 ) -> Result<(), PropertiesError> {1225 Self::check_property_key(&key)?;12261227 let key = scope.apply(key)?;1228 self.01229 .try_insert(key, value)1230 .map_err(|_| PropertiesError::PropertyLimitReached)?;12311232 Ok(())1233 }1234}12351236/// Alias for property permissions map.1237pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;12381239/// Wrapper for properties map with consumed space control.1240#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]1241pub struct Properties {1242 map: PropertiesMap<PropertyValue>,1243 consumed_space: u32,1244 space_limit: u32,1245}12461247impl Properties {1248 /// Create new properies container.1249 pub fn new(space_limit: u32) -> Self {1250 Self {1251 map: PropertiesMap::new(),1252 consumed_space: 0,1253 space_limit,1254 }1255 }12561257 /// Remove propery with appropiate key.1258 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {1259 let value = self.map.remove(key)?;12601261 if let Some(ref value) = value {1262 let value_len = value.len() as u32;1263 self.consumed_space -= value_len;1264 }12651266 Ok(value)1267 }12681269 /// Get property with appropriate key.1270 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {1271 self.map.get(key)1272 }1273}12741275impl IntoIterator for Properties {1276 type Item = (PropertyKey, PropertyValue);1277 type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;12781279 fn into_iter(self) -> Self::IntoIter {1280 self.map.into_iter()1281 }1282}12831284impl TrySetProperty for Properties {1285 type Value = PropertyValue;12861287 fn try_scoped_set(1288 &mut self,1289 scope: PropertyScope,1290 key: PropertyKey,1291 value: Self::Value,1292 ) -> Result<(), PropertiesError> {1293 let value_len = value.len();12941295 if self.consumed_space as usize + value_len > self.space_limit as usize1296 && !cfg!(feature = "runtime-benchmarks")1297 {1298 return Err(PropertiesError::NoSpaceForProperty);1299 }13001301 self.map.try_scoped_set(scope, key, value)?;13021303 self.consumed_space += value_len as u32;13041305 Ok(())1306 }1307}13081309/// Utility struct for using in `StorageMap`.1310pub struct CollectionProperties;13111312impl Get<Properties> for CollectionProperties {1313 fn get() -> Properties {1314 Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)1315 }1316}13171318/// Utility struct for using in `StorageMap`.1319pub struct TokenProperties;13201321impl Get<Properties> for TokenProperties {1322 fn get() -> Properties {1323 Properties::new(MAX_TOKEN_PROPERTIES_SIZE)1324 }1325}13261327// RMRK1328// todo document?1329parameter_types! {1330 #[derive(PartialEq, TypeInfo)]1331 pub const RmrkStringLimit: u32 = 128;1332 #[derive(PartialEq)]1333 pub const RmrkCollectionSymbolLimit: u32 = MAX_TOKEN_PREFIX_LENGTH;1334 #[derive(PartialEq)]1335 pub const RmrkResourceSymbolLimit: u32 = 10;1336 #[derive(PartialEq)]1337 pub const RmrkBaseSymbolLimit: u32 = MAX_TOKEN_PREFIX_LENGTH;1338 #[derive(PartialEq)]1339 pub const RmrkKeyLimit: u32 = 32;1340 #[derive(PartialEq)]1341 pub const RmrkValueLimit: u32 = 256;1342 #[derive(PartialEq)]1343 pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;1344 #[derive(PartialEq)]1345 pub const MaxPropertiesPerTheme: u32 = 5;1346 #[derive(PartialEq)]1347 pub const RmrkPartsLimit: u32 = 25;1348 #[derive(PartialEq)]1349 pub const RmrkMaxPriorities: u32 = 25;1350 #[derive(PartialEq)]1351 pub const MaxResourcesOnMint: u32 = 100;1352}13531354impl From<RmrkCollectionId> for CollectionId {1355 fn from(id: RmrkCollectionId) -> Self {1356 Self(id)1357 }1358}13591360impl From<RmrkNftId> for TokenId {1361 fn from(id: RmrkNftId) -> Self {1362 Self(id)1363 }1364}13651366pub type RmrkCollectionInfo<AccountId> =1367 CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;1368pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;1369pub type RmrkResourceInfo = ResourceInfo<RmrkString, RmrkBoundedParts>;1370pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;1371pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;1372pub type BoundedEquippableCollectionIds =1373 BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>;1374pub type RmrkPartType = PartType<RmrkString, BoundedEquippableCollectionIds>;1375pub type RmrkEquippableList = EquippableList<BoundedEquippableCollectionIds>;1376pub type RmrkThemeProperty = ThemeProperty<RmrkString>;1377pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;1378pub type RmrkBoundedTheme = Theme<RmrkString, BoundedVec<RmrkThemeProperty, MaxPropertiesPerTheme>>;1379pub type RmrkResourceTypes = ResourceTypes<RmrkString, RmrkBoundedParts>;13801381pub type RmrkBasicResource = BasicResource<RmrkString>;1382pub type RmrkComposableResource = ComposableResource<RmrkString, RmrkBoundedParts>;1383pub type RmrkSlotResource = SlotResource<RmrkString>;13841385pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;1386pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;1387pub type RmrkBaseSymbol = BoundedVec<u8, RmrkBaseSymbolLimit>;1388pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;1389pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;1390pub type RmrkBoundedResource = BoundedVec<u8, RmrkResourceSymbolLimit>;1391pub type RmrkBoundedParts = BoundedVec<RmrkPartId, RmrkPartsLimit>; // todo make sure it is needed13921393pub type RmrkRpcString = Vec<u8>;1394pub type RmrkThemeName = RmrkRpcString;1395pub type RmrkPropertyKey = RmrkRpcString;tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -102,6 +102,7 @@
"testXcmTransferStatemine": "mocha --timeout 9999999 -r ts-node/register ./**/xcm/xcmTransferStatemine.test.ts statemineId=1000 uniqueId=5000",
"testXcmTransferMoonbeam": "mocha --timeout 9999999 -r ts-node/register ./**/xcm/xcmTransferMoonbeam.test.ts",
"benchMintingFee": "ts-node src/benchmarks/mintFee/benchmark.ts",
+ "testApiConsts": "mocha --timeout 9999999 -r ts-node/register ./**/apiConsts.test.ts",
"load": "mocha --timeout 9999999 -r ts-node/register './**/*.load.ts'",
"loadTransfer": "ts-node src/transfer.nload.ts",
"polkadot-types-fetch-metadata": "curl -H 'Content-Type: application/json' -d '{\"id\":\"1\", \"jsonrpc\":\"2.0\", \"method\": \"state_getMetadata\", \"params\":[]}' http://localhost:9933 > src/interfaces/metadata.json",
tests/src/apiConsts.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/apiConsts.test.ts
@@ -0,0 +1,108 @@
+// 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/>.
+
+import {ApiPromise} from '@polkadot/api';
+import {usingPlaygrounds, itSub, expect} from './util';
+
+
+const MAX_COLLECTION_DESCRIPTION_LENGTH = 256n;
+const MAX_COLLECTION_NAME_LENGTH = 64n;
+const COLLECTION_ADMINS_LIMIT = 5n;
+const MAX_COLLECTION_PROPERTIES_SIZE = 40960n;
+const MAX_TOKEN_PREFIX_LENGTH = 16n;
+const MAX_PROPERTY_KEY_LENGTH = 256n;
+const MAX_PROPERTY_VALUE_LENGTH = 32768n;
+const MAX_PROPERTIES_PER_ITEM = 64n;
+const MAX_TOKEN_PROPERTIES_SIZE = 32768n;
+const NESTING_BUDGET = 5n;
+
+const DEFAULT_COLLETCTION_LIMIT = {
+ accountTokenOwnershipLimit: '1,000,000',
+ sponsoredDataSize: '2,048',
+ sponsoredDataRateLimit: 'SponsoringDisabled',
+ tokenLimit: '4,294,967,295',
+ sponsorTransferTimeout: '5',
+ sponsorApproveTimeout: '5',
+ ownerCanTransfer: false,
+ ownerCanDestroy: true,
+ transfersEnabled: true,
+};
+
+describe('integration test: API UNIQUE consts', () => {
+ let api: ApiPromise;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper) => {
+ api = await helper.getApi();
+ });
+ });
+
+ itSub('DEFAULT_NFT_COLLECTION_LIMITS', () => {
+ expect(api.consts.unique.nftDefaultCollectionLimits.toHuman()).to.deep.equal(DEFAULT_COLLETCTION_LIMIT);
+ });
+
+ itSub('DEFAULT_RFT_COLLECTION_LIMITS', () => {
+ expect(api.consts.unique.rftDefaultCollectionLimits.toHuman()).to.deep.equal(DEFAULT_COLLETCTION_LIMIT);
+ });
+
+ itSub('DEFAULT_FT_COLLECTION_LIMITS', () => {
+ expect(api.consts.unique.ftDefaultCollectionLimits.toHuman()).to.deep.equal(DEFAULT_COLLETCTION_LIMIT);
+ });
+
+ itSub('MAX_COLLECTION_NAME_LENGTH', () => {
+ checkConst(api.consts.unique.maxCollectionNameLength, MAX_COLLECTION_NAME_LENGTH);
+ });
+
+ itSub('MAX_COLLECTION_DESCRIPTION_LENGTH', () => {
+ checkConst(api.consts.unique.maxCollectionDescriptionLength, MAX_COLLECTION_DESCRIPTION_LENGTH);
+ });
+
+ itSub('MAX_COLLECTION_PROPERTIES_SIZE', () => {
+ checkConst(api.consts.unique.maxCollectionPropertiesSize, MAX_COLLECTION_PROPERTIES_SIZE);
+ });
+
+ itSub('MAX_TOKEN_PREFIX_LENGTH', () => {
+ checkConst(api.consts.unique.maxTokenPrefixLength, MAX_TOKEN_PREFIX_LENGTH);
+ });
+
+ itSub('MAX_PROPERTY_KEY_LENGTH', () => {
+ checkConst(api.consts.unique.maxPropertyKeyLength, MAX_PROPERTY_KEY_LENGTH);
+ });
+
+ itSub('MAX_PROPERTY_VALUE_LENGTH', () => {
+ checkConst(api.consts.unique.maxPropertyValueLength, MAX_PROPERTY_VALUE_LENGTH);
+ });
+
+ itSub('MAX_PROPERTIES_PER_ITEM', () => {
+ checkConst(api.consts.unique.maxPropertiesPerItem, MAX_PROPERTIES_PER_ITEM);
+ });
+
+ itSub('NESTING_BUDGET', () => {
+ checkConst(api.consts.unique.nestingBudget, NESTING_BUDGET);
+ });
+
+ itSub('MAX_TOKEN_PROPERTIES_SIZE', () => {
+ checkConst(api.consts.unique.maxTokenPropertiesSize, MAX_TOKEN_PROPERTIES_SIZE);
+ });
+
+ itSub('COLLECTION_ADMINS_LIMIT', () => {
+ checkConst(api.consts.unique.collectionAdminsLimit, COLLECTION_ADMINS_LIMIT);
+ });
+});
+
+function checkConst<T>(constValue: any, expectedValue: T) {
+ expect(constValue.toBigInt()).equal(expectedValue);
+}
tests/src/interfaces/augment-api-consts.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-consts.ts
+++ b/tests/src/interfaces/augment-api-consts.ts
@@ -9,7 +9,7 @@
import type { Option, u128, u16, u32, u64, u8 } from '@polkadot/types-codec';
import type { Codec } from '@polkadot/types-codec/types';
import type { Perbill, Permill, Weight } from '@polkadot/types/interfaces/runtime';
-import type { FrameSupportPalletId, FrameSystemLimitsBlockLength, FrameSystemLimitsBlockWeights, SpVersionRuntimeVersion, SpWeightsRuntimeDbWeight, XcmV1MultiLocation } from '@polkadot/types/lookup';
+import type { FrameSupportPalletId, FrameSystemLimitsBlockLength, FrameSystemLimitsBlockWeights, SpVersionRuntimeVersion, SpWeightsRuntimeDbWeight, UpDataStructsCollectionLimits, XcmV1MultiLocation } from '@polkadot/types/lookup';
export type __AugmentedConst<ApiType extends ApiTypes> = AugmentedConst<ApiType>;
@@ -231,6 +231,64 @@
**/
[key: string]: Codec;
};
+ unique: {
+ /**
+ * Maximum admins per collection.
+ **/
+ collectionAdminsLimit: u32 & AugmentedConst<ApiType>;
+ /**
+ * Default FT collection limit.
+ **/
+ ftDefaultCollectionLimits: UpDataStructsCollectionLimits & AugmentedConst<ApiType>;
+ /**
+ * Maximum length for collection description.
+ **/
+ maxCollectionDescriptionLength: u32 & AugmentedConst<ApiType>;
+ /**
+ * Maximum length for collection name.
+ **/
+ maxCollectionNameLength: u32 & AugmentedConst<ApiType>;
+ /**
+ * Maximum size for all collection properties.
+ **/
+ maxCollectionPropertiesSize: u32 & AugmentedConst<ApiType>;
+ /**
+ * Maximum properties that can be assigned to token.
+ **/
+ maxPropertiesPerItem: u32 & AugmentedConst<ApiType>;
+ /**
+ * Maximal lenght of property key.
+ **/
+ maxPropertyKeyLength: u32 & AugmentedConst<ApiType>;
+ /**
+ * Maximal lenght of property value.
+ **/
+ maxPropertyValueLength: u32 & AugmentedConst<ApiType>;
+ /**
+ * Maximal token prefix length.
+ **/
+ maxTokenPrefixLength: u32 & AugmentedConst<ApiType>;
+ /**
+ * Maximum size for all token properties.
+ **/
+ maxTokenPropertiesSize: u32 & AugmentedConst<ApiType>;
+ /**
+ * Maximum number of levels of depth in the token nesting tree.
+ **/
+ nestingBudget: u32 & AugmentedConst<ApiType>;
+ /**
+ * Default NFT collection limit.
+ **/
+ nftDefaultCollectionLimits: UpDataStructsCollectionLimits & AugmentedConst<ApiType>;
+ /**
+ * Default RFT collection limit.
+ **/
+ rftDefaultCollectionLimits: UpDataStructsCollectionLimits & AugmentedConst<ApiType>;
+ /**
+ * Generic const
+ **/
+ [key: string]: Codec;
+ };
vesting: {
/**
* The minimum amount transferred to call `vested_transfer`.