1234567891011121314151617#![cfg_attr(not(feature = "std"), no_std)]1819use core::{20 convert::{TryFrom, TryInto},21 fmt,22};23use frame_support::{24 storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},25 traits::Get,26 parameter_types,27};2829#[cfg(feature = "serde")]30use serde::{Serialize, Deserialize};3132use sp_core::U256;33use sp_runtime::{ArithmeticError, sp_std::prelude::Vec, Permill};34use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};35use frame_support::{BoundedVec, traits::ConstU32};36use derivative::Derivative;37use scale_info::TypeInfo;383940use rmrk_types::{41 CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme, ThemeProperty,42};43pub use rmrk_types::{44 primitives::{45 CollectionId as RmrkCollectionId, NftId as RmrkNftId, BaseId as RmrkBaseId,46 PartId as RmrkPartId, ResourceId as RmrkResourceId,47 },48 NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,49};5051mod bounded;52pub mod budget;53pub mod mapping;54mod migration;5556pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;57pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;58pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;5960pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {61 100_00062} else {63 1064};65pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {66 100_00067} else {68 1069};70pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {71 204872} else {73 1074};75pub const COLLECTION_ADMINS_LIMIT: u32 = 5;76pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;77pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {78 1_000_00079} else {80 1081};828384pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;85pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;86pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;8788pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;899091pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;92pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;93pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;9495pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;9697pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;98pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;99pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;100101pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;102pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;103pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;104105106pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;107pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;108109pub const MAX_COLLECTION_PROPERTIES_ENCODE_LEN: u32 =110 MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH + MAX_COLLECTION_PROPERTIES_SIZE;111112113pub const RMRK_STRING_LIMIT: u32 = 128;114pub const RMRK_COLLECTION_SYMBOL_LIMIT: u32 = 100;115pub const RMRK_RESOURCE_SYMBOL_LIMIT: u32 = 10;116pub const RMRK_KEY_LIMIT: u32 = 32;117pub const RMRK_VALUE_LIMIT: u32 = 256;118119pub struct MaxPropertiesPermissionsEncodeLen;120121impl Get<u32> for MaxPropertiesPermissionsEncodeLen {122 fn get() -> u32 {123 MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH124 + <PropertyPermission as MaxEncodedLen>::max_encoded_len() as u32125 }126}127128129130pub const MAX_ITEMS_PER_BATCH: u32 = 200;131132pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;133134#[derive(135 Encode,136 Decode,137 PartialEq,138 Eq,139 PartialOrd,140 Ord,141 Clone,142 Copy,143 Debug,144 Default,145 TypeInfo,146 MaxEncodedLen,147)]148#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]149pub struct CollectionId(pub u32);150impl EncodeLike<u32> for CollectionId {}151impl EncodeLike<CollectionId> for u32 {}152153#[derive(154 Encode,155 Decode,156 PartialEq,157 Eq,158 PartialOrd,159 Ord,160 Clone,161 Copy,162 Debug,163 Default,164 TypeInfo,165 MaxEncodedLen,166)]167#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]168pub struct TokenId(pub u32);169impl EncodeLike<u32> for TokenId {}170impl EncodeLike<TokenId> for u32 {}171172impl TokenId {173 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {174 self.0175 .checked_add(1)176 .ok_or(ArithmeticError::Overflow)177 .map(Self)178 }179}180181impl From<TokenId> for U256 {182 fn from(t: TokenId) -> Self {183 t.0.into()184 }185}186187impl TryFrom<U256> for TokenId {188 type Error = &'static str;189190 fn try_from(value: U256) -> Result<Self, Self::Error> {191 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))192 }193}194195#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]196#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]197pub struct TokenData<CrossAccountId> {198 pub const_data: Vec<u8>,199 pub properties: Vec<Property>,200 pub owner: Option<CrossAccountId>,201}202203pub struct OverflowError;204impl From<OverflowError> for &'static str {205 fn from(_: OverflowError) -> Self {206 "overflow occured"207 }208}209210pub type DecimalPoints = u8;211212#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]213#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]214pub enum CollectionMode {215 NFT,216 217 Fungible(DecimalPoints),218 ReFungible,219}220221impl CollectionMode {222 pub fn id(&self) -> u8 {223 match self {224 CollectionMode::NFT => 1,225 CollectionMode::Fungible(_) => 2,226 CollectionMode::ReFungible => 3,227 }228 }229}230231pub trait SponsoringResolve<AccountId, Call> {232 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;233}234235#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]236#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]237pub enum AccessMode {238 Normal,239 AllowList,240}241impl Default for AccessMode {242 fn default() -> Self {243 Self::Normal244 }245}246247#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]248#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]249pub enum SchemaVersion {250 ImageURL,251 Unique,252}253impl Default for SchemaVersion {254 fn default() -> Self {255 Self::ImageURL256 }257}258259#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]260#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]261pub struct Ownership<AccountId> {262 pub owner: AccountId,263 pub fraction: u128,264}265266#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]267#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]268pub enum SponsorshipState<AccountId> {269 270 Disabled,271 Unconfirmed(AccountId),272 273 Confirmed(AccountId),274}275276impl<AccountId> SponsorshipState<AccountId> {277 pub fn sponsor(&self) -> Option<&AccountId> {278 match self {279 Self::Confirmed(sponsor) => Some(sponsor),280 _ => None,281 }282 }283284 pub fn pending_sponsor(&self) -> Option<&AccountId> {285 match self {286 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),287 _ => None,288 }289 }290291 pub fn confirmed(&self) -> bool {292 matches!(self, Self::Confirmed(_))293 }294}295296impl<T> Default for SponsorshipState<T> {297 fn default() -> Self {298 Self::Disabled299 }300}301302303#[struct_versioning::versioned(version = 2, upper)]304#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]305pub struct Collection<AccountId> {306 pub owner: AccountId,307 pub mode: CollectionMode,308 pub access: AccessMode,309 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,310 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,311 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,312 pub mint_mode: bool,313314 #[version(..2)]315 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,316317 pub schema_version: SchemaVersion,318 pub sponsorship: SponsorshipState<AccountId>,319320 #[version(..2)]321 pub limits: CollectionLimitsVersion1, 322 #[version(2.., upper(limits.into()))]323 pub limits: CollectionLimitsVersion2,324325 #[version(..2)]326 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,327328 #[version(..2)]329 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,330331 #[version(..2)]332 pub meta_update_permission: MetaUpdatePermission,333}334335336#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]337#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]338pub struct RpcCollection<AccountId> {339 pub owner: AccountId,340 pub mode: CollectionMode,341 pub access: AccessMode,342 pub name: Vec<u16>,343 pub description: Vec<u16>,344 pub token_prefix: Vec<u8>,345 pub mint_mode: bool,346 pub offchain_schema: Vec<u8>,347 pub schema_version: SchemaVersion,348 pub sponsorship: SponsorshipState<AccountId>,349 pub limits: CollectionLimits,350 pub const_on_chain_schema: Vec<u8>,351 pub token_property_permissions: Vec<PropertyKeyPermission>,352 pub properties: Vec<Property>,353}354355#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]356#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]357pub enum CollectionField {358 ConstOnChainSchema,359 OffchainSchema,360}361362#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]363#[derivative(Debug, Default(bound = ""))]364pub struct CreateCollectionData<AccountId> {365 #[derivative(Default(value = "CollectionMode::NFT"))]366 pub mode: CollectionMode,367 pub access: Option<AccessMode>,368 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,369 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,370 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,371 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,372 pub schema_version: Option<SchemaVersion>,373 pub pending_sponsor: Option<AccountId>,374 pub limits: Option<CollectionLimits>,375 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,376 pub token_property_permissions: CollectionPropertiesPermissionsVec,377 pub properties: CollectionPropertiesVec,378}379380pub type CollectionPropertiesPermissionsVec =381 BoundedVec<PropertyKeyPermission, MaxPropertiesPermissionsEncodeLen>;382383pub type CollectionPropertiesVec =384 BoundedVec<Property, ConstU32<MAX_COLLECTION_PROPERTIES_ENCODE_LEN>>;385386387#[struct_versioning::versioned(version = 2, upper)]388#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]389#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]390pub struct CollectionLimits {391 pub account_token_ownership_limit: Option<u32>,392 pub sponsored_data_size: Option<u32>,393394 395 396 397 398 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,399 pub token_limit: Option<u32>,400401 402 pub sponsor_transfer_timeout: Option<u32>,403 pub sponsor_approve_timeout: Option<u32>,404 pub owner_can_transfer: Option<bool>,405 pub owner_can_destroy: Option<bool>,406 pub transfers_enabled: Option<bool>,407408 #[version(2.., upper(None))]409 pub nesting_rule: Option<NestingRule>,410}411412impl CollectionLimits {413 pub fn account_token_ownership_limit(&self) -> u32 {414 self.account_token_ownership_limit415 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)416 .min(MAX_TOKEN_OWNERSHIP)417 }418 pub fn sponsored_data_size(&self) -> u32 {419 self.sponsored_data_size420 .unwrap_or(CUSTOM_DATA_LIMIT)421 .min(CUSTOM_DATA_LIMIT)422 }423 pub fn token_limit(&self) -> u32 {424 self.token_limit425 .unwrap_or(COLLECTION_TOKEN_LIMIT)426 .min(COLLECTION_TOKEN_LIMIT)427 }428 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {429 self.sponsor_transfer_timeout430 .unwrap_or(default)431 .min(MAX_SPONSOR_TIMEOUT)432 }433 pub fn sponsor_approve_timeout(&self) -> u32 {434 self.sponsor_approve_timeout435 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)436 .min(MAX_SPONSOR_TIMEOUT)437 }438 pub fn owner_can_transfer(&self) -> bool {439 self.owner_can_transfer.unwrap_or(true)440 }441 pub fn owner_can_destroy(&self) -> bool {442 self.owner_can_destroy.unwrap_or(true)443 }444 pub fn transfers_enabled(&self) -> bool {445 self.transfers_enabled.unwrap_or(true)446 }447 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {448 match self449 .sponsored_data_rate_limit450 .unwrap_or(SponsoringRateLimit::SponsoringDisabled)451 {452 SponsoringRateLimit::SponsoringDisabled => None,453 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),454 }455 }456 pub fn nesting_rule(&self) -> &NestingRule {457 static DEFAULT: NestingRule = NestingRule::Disabled;458 self.nesting_rule.as_ref().unwrap_or(&DEFAULT)459 }460}461462#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]463#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]464#[derivative(Debug)]465pub enum NestingRule {466 467 Disabled,468 469 Owner,470 471 OwnerRestricted(472 #[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]473 #[derivative(Debug(format_with = "bounded::set_debug"))]474 BoundedBTreeSet<CollectionId, ConstU32<16>>,475 ),476}477478#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]479#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]480pub enum SponsoringRateLimit {481 SponsoringDisabled,482 Blocks(u32),483}484485#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]486#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]487#[derivative(Debug)]488pub struct CreateNftData {489 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]490 #[derivative(Debug(format_with = "bounded::vec_debug"))]491 pub const_data: BoundedVec<u8, CustomDataLimit>,492493 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]494 #[derivative(Debug(format_with = "bounded::vec_debug"))]495 pub properties: CollectionPropertiesVec,496}497498#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]499#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]500pub struct CreateFungibleData {501 pub value: u128,502}503504#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]505#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]506#[derivative(Debug)]507pub struct CreateReFungibleData {508 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]509 #[derivative(Debug(format_with = "bounded::vec_debug"))]510 pub const_data: BoundedVec<u8, CustomDataLimit>,511 pub pieces: u128,512}513514#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]515pub enum MetaUpdatePermission {516 ItemOwner,517 Admin,518 None,519}520521#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]522#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]523pub enum CreateItemData {524 NFT(CreateNftData),525 Fungible(CreateFungibleData),526 ReFungible(CreateReFungibleData),527}528529#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]530#[derivative(Debug)]531pub struct CreateNftExData<CrossAccountId> {532 #[derivative(Debug(format_with = "bounded::vec_debug"))]533 pub const_data: BoundedVec<u8, CustomDataLimit>,534 #[derivative(Debug(format_with = "bounded::vec_debug"))]535 pub properties: CollectionPropertiesVec,536 pub owner: CrossAccountId,537}538539#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]540#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]541pub struct CreateRefungibleExData<CrossAccountId> {542 #[derivative(Debug(format_with = "bounded::vec_debug"))]543 pub const_data: BoundedVec<u8, CustomDataLimit>,544 #[derivative(Debug(format_with = "bounded::map_debug"))]545 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,546}547548#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]549#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]550pub enum CreateItemExData<CrossAccountId> {551 NFT(552 #[derivative(Debug(format_with = "bounded::vec_debug"))]553 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,554 ),555 Fungible(556 #[derivative(Debug(format_with = "bounded::map_debug"))]557 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,558 ),559 560 RefungibleMultipleItems(561 #[derivative(Debug(format_with = "bounded::vec_debug"))]562 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,563 ),564 565 RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),566}567568impl CreateItemData {569 pub fn data_size(&self) -> usize {570 match self {571 CreateItemData::NFT(data) => data.const_data.len(),572 CreateItemData::ReFungible(data) => data.const_data.len(),573 _ => 0,574 }575 }576}577578impl From<CreateNftData> for CreateItemData {579 fn from(item: CreateNftData) -> Self {580 CreateItemData::NFT(item)581 }582}583584impl From<CreateReFungibleData> for CreateItemData {585 fn from(item: CreateReFungibleData) -> Self {586 CreateItemData::ReFungible(item)587 }588}589590impl From<CreateFungibleData> for CreateItemData {591 fn from(item: CreateFungibleData) -> Self {592 CreateItemData::Fungible(item)593 }594}595596#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]597#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]598pub struct CollectionStats {599 pub created: u32,600 pub destroyed: u32,601 pub alive: u32,602}603604#[derive(Encode, Decode, Clone, Debug)]605#[cfg_attr(feature = "std", derive(PartialEq))]606pub struct PhantomType<T>(core::marker::PhantomData<T>);607608impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {609 type Identity = PhantomType<T>;610611 fn type_info() -> scale_info::Type {612 use scale_info::{613 Type, Path,614 build::{FieldsBuilder, UnnamedFields},615 type_params,616 };617 Type::builder()618 .path(Path::new("up_data_structs", "PhantomType"))619 .type_params(type_params!(T))620 .composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))621 }622}623impl<T> MaxEncodedLen for PhantomType<T> {624 fn max_encoded_len() -> usize {625 0626 }627}628629pub type PropertyKey = BoundedVec<u8, ConstU32<MAX_PROPERTY_KEY_LENGTH>>;630pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;631632#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]633#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]634pub struct PropertyPermission {635 pub mutable: bool,636 pub collection_admin: bool,637 pub token_owner: bool,638}639640impl PropertyPermission {641 pub fn none() -> Self {642 Self {643 mutable: true,644 collection_admin: false,645 token_owner: false,646 }647 }648}649650#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]651#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]652pub struct Property {653 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]654 pub key: PropertyKey,655656 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]657 pub value: PropertyValue,658}659660#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]661#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]662pub struct PropertyKeyPermission {663 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]664 pub key: PropertyKey,665666 pub permission: PropertyPermission,667}668669pub enum PropertiesError {670 NoSpaceForProperty,671 PropertyLimitReached,672 InvalidCharacterInPropertyKey,673 PropertyKeyIsTooLong,674 EmptyPropertyKey,675}676677#[derive(Clone, Copy)]678pub enum PropertyScope {679 None,680 Rmrk,681}682683impl PropertyScope {684 fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {685 let scope_str: &[u8] = match self {686 Self::None => return Ok(key),687 Self::Rmrk => b"rmrk",688 };689690 [scope_str, b":", key.as_slice()]691 .concat()692 .try_into()693 .map_err(|_| PropertiesError::PropertyKeyIsTooLong)694 }695}696697pub trait TrySetProperty: Sized {698 type Value;699700 fn try_scoped_set(701 &mut self,702 scope: PropertyScope,703 key: PropertyKey,704 value: Self::Value,705 ) -> Result<(), PropertiesError>;706707 fn try_scoped_set_from_iter<I>(708 &mut self,709 scope: PropertyScope,710 iter: I,711 ) -> Result<(), PropertiesError>712 where713 I: Iterator<Item = (PropertyKey, Self::Value)>,714 {715 for (key, value) in iter {716 self.try_scoped_set(scope, key, value)?;717 }718719 Ok(())720 }721722 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {723 self.try_scoped_set(PropertyScope::None, key, value)724 }725726 fn try_set_from_iter<I>(&mut self, iter: I) -> Result<(), PropertiesError>727 where728 I: Iterator<Item = (PropertyKey, Self::Value)>,729 {730 self.try_scoped_set_from_iter(PropertyScope::None, iter)731 }732}733734#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]735#[derivative(Default(bound = ""))]736pub struct PropertiesMap<Value>(737 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,738);739740impl<Value> PropertiesMap<Value> {741 pub fn new() -> Self {742 Self(BoundedBTreeMap::new())743 }744745 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {746 Self::check_property_key(key)?;747748 Ok(self.0.remove(key))749 }750751 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {752 self.0.get(key)753 }754755 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &Value)> {756 self.0.iter()757 }758759 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {760 if key.is_empty() {761 return Err(PropertiesError::EmptyPropertyKey);762 }763764 for byte in key.as_slice().iter() {765 let byte = *byte;766767 if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' {768 return Err(PropertiesError::InvalidCharacterInPropertyKey);769 }770 }771772 Ok(())773 }774}775776impl<Value> TrySetProperty for PropertiesMap<Value> {777 type Value = Value;778779 fn try_scoped_set(780 &mut self,781 scope: PropertyScope,782 key: PropertyKey,783 value: Self::Value,784 ) -> Result<(), PropertiesError> {785 Self::check_property_key(&key)?;786787 let key = scope.apply(key)?;788 self.0789 .try_insert(key, value)790 .map_err(|_| PropertiesError::PropertyLimitReached)?;791792 Ok(())793 }794}795796pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;797798#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]799pub struct Properties {800 map: PropertiesMap<PropertyValue>,801 consumed_space: u32,802 space_limit: u32,803}804805impl Properties {806 pub fn new(space_limit: u32) -> Self {807 Self {808 map: PropertiesMap::new(),809 consumed_space: 0,810 space_limit,811 }812 }813814 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {815 let value = self.map.remove(key)?;816817 if let Some(ref value) = value {818 let value_len = value.len() as u32;819 self.consumed_space -= value_len;820 }821822 Ok(value)823 }824825 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {826 self.map.get(key)827 }828829 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {830 self.map.iter()831 }832}833834impl TrySetProperty for Properties {835 type Value = PropertyValue;836837 fn try_scoped_set(838 &mut self,839 scope: PropertyScope,840 key: PropertyKey,841 value: Self::Value,842 ) -> Result<(), PropertiesError> {843 let value_len = value.len();844845 if self.consumed_space as usize + value_len > self.space_limit as usize {846 return Err(PropertiesError::NoSpaceForProperty);847 }848849 self.map.try_scoped_set(scope, key, value)?;850851 self.consumed_space += value_len as u32;852853 Ok(())854 }855}856857pub struct CollectionProperties;858859impl Get<Properties> for CollectionProperties {860 fn get() -> Properties {861 Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)862 }863}864865pub struct TokenProperties;866867impl Get<Properties> for TokenProperties {868 fn get() -> Properties {869 Properties::new(MAX_TOKEN_PROPERTIES_SIZE)870 }871}872873874875parameter_types! {876 #[derive(PartialEq, TypeInfo)]877 pub const RmrkStringLimit: u32 = 128;878 #[derive(PartialEq)]879 pub const RmrkCollectionSymbolLimit: u32 = 100;880 #[derive(PartialEq)]881 pub const RmrkResourceSymbolLimit: u32 = 10;882 #[derive(PartialEq)]883 pub const RmrkKeyLimit: u32 = 32;884 #[derive(PartialEq)]885 pub const RmrkValueLimit: u32 = 256;886 #[derive(PartialEq)]887 pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;888 #[derive(PartialEq)]889 pub const RmrkPartsLimit: u32 = 3;890}891892pub type RmrkCollectionInfo<AccountId> =893 CollectionInfo<RmrkString, BoundedVec<u8, RmrkCollectionSymbolLimit>, AccountId>;894pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;895pub type RmrkResourceInfo = ResourceInfo<896 BoundedVec<u8, RmrkResourceSymbolLimit>,897 RmrkString,898 BoundedVec<RmrkPartId, RmrkPartsLimit>,899>;900pub type RmrkPropertyInfo =901 PropertyInfo<BoundedVec<u8, RmrkKeyLimit>, BoundedVec<u8, RmrkValueLimit>>;902pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;903pub type RmrkPartType =904 PartType<RmrkString, BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>>;905pub type RmrkTheme = Theme<RmrkString, Vec<ThemeProperty<RmrkString>>>;906907pub type RmrkRpcString = Vec<u8>;908pub type RmrkThemeName = RmrkRpcString;909pub type RmrkPropertyKey = RmrkRpcString;910911type RmrkString = BoundedVec<u8, RmrkStringLimit>;