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}659660impl Into<(PropertyKey, PropertyValue)> for Property {661 fn into(self) -> (PropertyKey, PropertyValue) {662 (self.key, self.value)663 }664}665666#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]667#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]668pub struct PropertyKeyPermission {669 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]670 pub key: PropertyKey,671672 pub permission: PropertyPermission,673}674675impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {676 fn into(self) -> (PropertyKey, PropertyPermission) {677 (self.key, self.permission)678 }679}680681#[derive(Debug)]682pub enum PropertiesError {683 NoSpaceForProperty,684 PropertyLimitReached,685 InvalidCharacterInPropertyKey,686 PropertyKeyIsTooLong,687 EmptyPropertyKey,688}689690#[derive(Clone, Copy)]691pub enum PropertyScope {692 None,693 Rmrk,694}695696impl PropertyScope {697 pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {698 let scope_str: &[u8] = match self {699 Self::None => return Ok(key),700 Self::Rmrk => b"rmrk",701 };702703 [scope_str, b":", key.as_slice()]704 .concat()705 .try_into()706 .map_err(|_| PropertiesError::PropertyKeyIsTooLong)707 }708}709710pub trait TrySetProperty: Sized {711 type Value;712713 fn try_scoped_set(714 &mut self,715 scope: PropertyScope,716 key: PropertyKey,717 value: Self::Value,718 ) -> Result<(), PropertiesError>;719720 fn try_scoped_set_from_iter<I, KV>(721 &mut self,722 scope: PropertyScope,723 iter: I,724 ) -> Result<(), PropertiesError>725 where726 I: Iterator<Item=KV>,727 KV: Into<(PropertyKey, Self::Value)>728 {729 for kv in iter {730 let (key, value) = kv.into();731 self.try_scoped_set(scope, key, value)?;732 }733734 Ok(())735 }736737 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {738 self.try_scoped_set(PropertyScope::None, key, value)739 }740741 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>742 where743 I: Iterator<Item=KV>,744 KV: Into<(PropertyKey, Self::Value)>745 {746 self.try_scoped_set_from_iter(PropertyScope::None, iter)747 }748}749750#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]751#[derivative(Default(bound = ""))]752pub struct PropertiesMap<Value>(753 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,754);755756impl<Value> PropertiesMap<Value> {757 pub fn new() -> Self {758 Self(BoundedBTreeMap::new())759 }760761 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {762 Self::check_property_key(key)?;763764 Ok(self.0.remove(key))765 }766767 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {768 self.0.get(key)769 }770771 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &Value)> {772 self.0.iter()773 }774775 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {776 if key.is_empty() {777 return Err(PropertiesError::EmptyPropertyKey);778 }779780 for byte in key.as_slice().iter() {781 let byte = *byte;782783 if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' {784 return Err(PropertiesError::InvalidCharacterInPropertyKey);785 }786 }787788 Ok(())789 }790}791792impl<Value> TrySetProperty for PropertiesMap<Value> {793 type Value = Value;794795 fn try_scoped_set(796 &mut self,797 scope: PropertyScope,798 key: PropertyKey,799 value: Self::Value,800 ) -> Result<(), PropertiesError> {801 Self::check_property_key(&key)?;802803 let key = scope.apply(key)?;804 self.0805 .try_insert(key, value)806 .map_err(|_| PropertiesError::PropertyLimitReached)?;807808 Ok(())809 }810}811812pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;813814#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]815pub struct Properties {816 map: PropertiesMap<PropertyValue>,817 consumed_space: u32,818 space_limit: u32,819}820821impl Properties {822 pub fn new(space_limit: u32) -> Self {823 Self {824 map: PropertiesMap::new(),825 consumed_space: 0,826 space_limit,827 }828 }829830 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {831 let value = self.map.remove(key)?;832833 if let Some(ref value) = value {834 let value_len = value.len() as u32;835 self.consumed_space -= value_len;836 }837838 Ok(value)839 }840841 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {842 self.map.get(key)843 }844845 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {846 self.map.iter()847 }848}849850impl TrySetProperty for Properties {851 type Value = PropertyValue;852853 fn try_scoped_set(854 &mut self,855 scope: PropertyScope,856 key: PropertyKey,857 value: Self::Value,858 ) -> Result<(), PropertiesError> {859 let value_len = value.len();860861 if self.consumed_space as usize + value_len > self.space_limit as usize {862 return Err(PropertiesError::NoSpaceForProperty);863 }864865 self.map.try_scoped_set(scope, key, value)?;866867 self.consumed_space += value_len as u32;868869 Ok(())870 }871}872873pub struct CollectionProperties;874875impl Get<Properties> for CollectionProperties {876 fn get() -> Properties {877 Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)878 }879}880881pub struct TokenProperties;882883impl Get<Properties> for TokenProperties {884 fn get() -> Properties {885 Properties::new(MAX_TOKEN_PROPERTIES_SIZE)886 }887}888889890891parameter_types! {892 #[derive(PartialEq, TypeInfo)]893 pub const RmrkStringLimit: u32 = 128;894 #[derive(PartialEq)]895 pub const RmrkCollectionSymbolLimit: u32 = 100;896 #[derive(PartialEq)]897 pub const RmrkResourceSymbolLimit: u32 = 10;898 #[derive(PartialEq)]899 pub const RmrkKeyLimit: u32 = 32;900 #[derive(PartialEq)]901 pub const RmrkValueLimit: u32 = 256;902 #[derive(PartialEq)]903 pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;904 #[derive(PartialEq)]905 pub const RmrkPartsLimit: u32 = 3;906}907908impl From<RmrkCollectionId> for CollectionId {909 fn from(id: RmrkCollectionId) -> Self {910 Self(id)911 }912}913914impl From<RmrkNftId> for TokenId {915 fn from(id: RmrkNftId) -> Self {916 Self(id)917 }918}919920pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;921pub type RmrkCollectionInfo<AccountId> = CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;922pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;923pub type RmrkResourceInfo = ResourceInfo<924 BoundedVec<u8, RmrkResourceSymbolLimit>,925 RmrkString,926 BoundedVec<RmrkPartId, RmrkPartsLimit>,927>;928pub type RmrkPropertyInfo =929 PropertyInfo<BoundedVec<u8, RmrkKeyLimit>, BoundedVec<u8, RmrkValueLimit>>;930pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;931pub type RmrkPartType =932 PartType<RmrkString, BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>>;933pub type RmrkTheme = Theme<RmrkString, Vec<ThemeProperty<RmrkString>>>;934935pub type RmrkRpcString = Vec<u8>;936pub type RmrkThemeName = RmrkRpcString;937pub type RmrkPropertyKey = RmrkRpcString;938939pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;