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;3839pub mod rmrk;404142use rmrk::{43 CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme, ThemeProperty,44};45pub use rmrk::{46 primitives::{47 CollectionId as RmrkCollectionId, NftId as RmrkNftId, BaseId as RmrkBaseId,48 PartId as RmrkPartId, ResourceId as RmrkResourceId,49 },50 NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,51 FixedPart as RmrkFixedPart, SlotPart as RmrkSlotPart, EquippableList as RmrkEquippableList,52 BasicResource as RmrkBasicResource, ComposableResource as RmrkComposableResource,53 SlotResource as RmrkSlotResource,54};5556mod bounded;57pub mod budget;58pub mod mapping;59mod migration;6061pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;62pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;63pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;6465pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {66 100_00067} else {68 1069};70pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {71 100_00072} else {73 1074};75pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {76 204877} else {78 1079};80pub const COLLECTION_ADMINS_LIMIT: u32 = 5;81pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;82pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {83 1_000_00084} else {85 1086};878889pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;90pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;91pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;9293pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;949596pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;97pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;98pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;99100pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;101102pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;103pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;104pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;105106pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;107pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;108pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;109110pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;111pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;112113114pub const RMRK_STRING_LIMIT: u32 = 128;115pub const RMRK_COLLECTION_SYMBOL_LIMIT: u32 = 100;116pub const RMRK_RESOURCE_SYMBOL_LIMIT: u32 = 10;117pub const RMRK_KEY_LIMIT: u32 = 32;118pub const RMRK_VALUE_LIMIT: u32 = 256;119120121122pub const MAX_ITEMS_PER_BATCH: u32 = 200;123124pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;125126#[derive(127 Encode,128 Decode,129 PartialEq,130 Eq,131 PartialOrd,132 Ord,133 Clone,134 Copy,135 Debug,136 Default,137 TypeInfo,138 MaxEncodedLen,139)]140#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]141pub struct CollectionId(pub u32);142impl EncodeLike<u32> for CollectionId {}143impl EncodeLike<CollectionId> for u32 {}144145#[derive(146 Encode,147 Decode,148 PartialEq,149 Eq,150 PartialOrd,151 Ord,152 Clone,153 Copy,154 Debug,155 Default,156 TypeInfo,157 MaxEncodedLen,158)]159#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]160pub struct TokenId(pub u32);161impl EncodeLike<u32> for TokenId {}162impl EncodeLike<TokenId> for u32 {}163164impl TokenId {165 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {166 self.0167 .checked_add(1)168 .ok_or(ArithmeticError::Overflow)169 .map(Self)170 }171}172173impl From<TokenId> for U256 {174 fn from(t: TokenId) -> Self {175 t.0.into()176 }177}178179impl TryFrom<U256> for TokenId {180 type Error = &'static str;181182 fn try_from(value: U256) -> Result<Self, Self::Error> {183 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))184 }185}186187#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]188#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]189pub struct TokenData<CrossAccountId> {190 pub properties: Vec<Property>,191 pub owner: Option<CrossAccountId>,192}193194pub struct OverflowError;195impl From<OverflowError> for &'static str {196 fn from(_: OverflowError) -> Self {197 "overflow occured"198 }199}200201pub type DecimalPoints = u8;202203#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]204#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]205pub enum CollectionMode {206 NFT,207 208 Fungible(DecimalPoints),209 ReFungible,210}211212impl CollectionMode {213 pub fn id(&self) -> u8 {214 match self {215 CollectionMode::NFT => 1,216 CollectionMode::Fungible(_) => 2,217 CollectionMode::ReFungible => 3,218 }219 }220}221222pub trait SponsoringResolve<AccountId, Call> {223 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;224}225226#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]227#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]228pub enum AccessMode {229 Normal,230 AllowList,231}232impl Default for AccessMode {233 fn default() -> Self {234 Self::Normal235 }236}237238#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]239#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]240pub enum SchemaVersion {241 ImageURL,242 Unique,243}244impl Default for SchemaVersion {245 fn default() -> Self {246 Self::ImageURL247 }248}249250#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]251#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]252pub struct Ownership<AccountId> {253 pub owner: AccountId,254 pub fraction: u128,255}256257#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]258#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]259pub enum SponsorshipState<AccountId> {260 261 Disabled,262 Unconfirmed(AccountId),263 264 Confirmed(AccountId),265}266267impl<AccountId> SponsorshipState<AccountId> {268 pub fn sponsor(&self) -> Option<&AccountId> {269 match self {270 Self::Confirmed(sponsor) => Some(sponsor),271 _ => None,272 }273 }274275 pub fn pending_sponsor(&self) -> Option<&AccountId> {276 match self {277 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),278 _ => None,279 }280 }281282 pub fn confirmed(&self) -> bool {283 matches!(self, Self::Confirmed(_))284 }285}286287impl<T> Default for SponsorshipState<T> {288 fn default() -> Self {289 Self::Disabled290 }291}292293294#[struct_versioning::versioned(version = 2, upper)]295#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]296pub struct Collection<AccountId> {297 pub owner: AccountId,298 pub mode: CollectionMode,299 #[version(..2)]300 pub access: AccessMode,301 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,302 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,303 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,304305 #[version(..2)]306 pub mint_mode: bool,307308 #[version(..2)]309 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,310311 #[version(..2)]312 pub schema_version: SchemaVersion,313 pub sponsorship: SponsorshipState<AccountId>,314315 pub limits: CollectionLimits,316317 #[version(2.., upper(Default::default()))]318 pub permissions: CollectionPermissions,319320 #[version(..2)]321 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,322323 #[version(..2)]324 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,325326 #[version(..2)]327 pub meta_update_permission: MetaUpdatePermission,328}329330331#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]332#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]333pub struct RpcCollection<AccountId> {334 pub owner: AccountId,335 pub mode: CollectionMode,336 pub name: Vec<u16>,337 pub description: Vec<u16>,338 pub token_prefix: Vec<u8>,339 pub sponsorship: SponsorshipState<AccountId>,340 pub limits: CollectionLimits,341 pub permissions: CollectionPermissions,342 pub token_property_permissions: Vec<PropertyKeyPermission>,343 pub properties: Vec<Property>,344}345346#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]347#[derivative(Debug, Default(bound = ""))]348pub struct CreateCollectionData<AccountId> {349 #[derivative(Default(value = "CollectionMode::NFT"))]350 pub mode: CollectionMode,351 pub access: Option<AccessMode>,352 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,353 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,354 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,355 pub pending_sponsor: Option<AccountId>,356 pub limits: Option<CollectionLimits>,357 pub permissions: Option<CollectionPermissions>,358 pub token_property_permissions: CollectionPropertiesPermissionsVec,359 pub properties: CollectionPropertiesVec,360}361362pub type CollectionPropertiesPermissionsVec =363 BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;364365pub type CollectionPropertiesVec = BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;366367368369#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]370#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]371pub struct CollectionLimits {372 pub account_token_ownership_limit: Option<u32>,373 pub sponsored_data_size: Option<u32>,374375 376 377 378 379 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,380 pub token_limit: Option<u32>,381382 383 pub sponsor_transfer_timeout: Option<u32>,384 pub sponsor_approve_timeout: Option<u32>,385 pub owner_can_transfer: Option<bool>,386 pub owner_can_destroy: Option<bool>,387 pub transfers_enabled: Option<bool>,388}389390impl CollectionLimits {391 pub fn account_token_ownership_limit(&self) -> u32 {392 self.account_token_ownership_limit393 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)394 .min(MAX_TOKEN_OWNERSHIP)395 }396 pub fn sponsored_data_size(&self) -> u32 {397 self.sponsored_data_size398 .unwrap_or(CUSTOM_DATA_LIMIT)399 .min(CUSTOM_DATA_LIMIT)400 }401 pub fn token_limit(&self) -> u32 {402 self.token_limit403 .unwrap_or(COLLECTION_TOKEN_LIMIT)404 .min(COLLECTION_TOKEN_LIMIT)405 }406 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {407 self.sponsor_transfer_timeout408 .unwrap_or(default)409 .min(MAX_SPONSOR_TIMEOUT)410 }411 pub fn sponsor_approve_timeout(&self) -> u32 {412 self.sponsor_approve_timeout413 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)414 .min(MAX_SPONSOR_TIMEOUT)415 }416 pub fn owner_can_transfer(&self) -> bool {417 self.owner_can_transfer.unwrap_or(true)418 }419 pub fn owner_can_destroy(&self) -> bool {420 self.owner_can_destroy.unwrap_or(true)421 }422 pub fn transfers_enabled(&self) -> bool {423 self.transfers_enabled.unwrap_or(true)424 }425 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {426 match self427 .sponsored_data_rate_limit428 .unwrap_or(SponsoringRateLimit::SponsoringDisabled)429 {430 SponsoringRateLimit::SponsoringDisabled => None,431 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),432 }433 }434}435436437#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]438#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]439pub struct CollectionPermissions {440 pub access: Option<AccessMode>,441 pub mint_mode: Option<bool>,442 pub nesting: Option<NestingRule>,443}444445impl CollectionPermissions {446 pub fn access(&self) -> AccessMode {447 self.access.unwrap_or(AccessMode::Normal)448 }449 pub fn mint_mode(&self) -> bool {450 self.mint_mode.unwrap_or(false)451 }452 pub fn nesting(&self) -> &NestingRule {453 static DEFAULT: NestingRule = NestingRule::Disabled;454 self.nesting.as_ref().unwrap_or(&DEFAULT)455 }456}457458#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]459#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]460#[derivative(Debug)]461pub enum NestingRule {462 463 Disabled,464 465 Owner,466 467 OwnerRestricted(468 #[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]469 #[derivative(Debug(format_with = "bounded::set_debug"))]470 BoundedBTreeSet<CollectionId, ConstU32<16>>,471 ),472 473 Permissive,474}475476#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]477#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]478pub enum SponsoringRateLimit {479 SponsoringDisabled,480 Blocks(u32),481}482483#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]484#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]485#[derivative(Debug)]486pub struct CreateNftData {487 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]488 #[derivative(Debug(format_with = "bounded::vec_debug"))]489 pub properties: CollectionPropertiesVec,490}491492#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]493#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]494pub struct CreateFungibleData {495 pub value: u128,496}497498#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]499#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]500#[derivative(Debug)]501pub struct CreateReFungibleData {502 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]503 #[derivative(Debug(format_with = "bounded::vec_debug"))]504 pub const_data: BoundedVec<u8, CustomDataLimit>,505 pub pieces: u128,506}507508#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]509#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]510pub enum MetaUpdatePermission {511 ItemOwner,512 Admin,513 None,514}515516#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]517#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]518pub enum CreateItemData {519 NFT(CreateNftData),520 Fungible(CreateFungibleData),521 ReFungible(CreateReFungibleData),522}523524#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]525#[derivative(Debug)]526pub struct CreateNftExData<CrossAccountId> {527 #[derivative(Debug(format_with = "bounded::vec_debug"))]528 pub properties: CollectionPropertiesVec,529 pub owner: CrossAccountId,530}531532#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]533#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]534pub struct CreateRefungibleExData<CrossAccountId> {535 #[derivative(Debug(format_with = "bounded::vec_debug"))]536 pub const_data: BoundedVec<u8, CustomDataLimit>,537 #[derivative(Debug(format_with = "bounded::map_debug"))]538 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,539}540541#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]542#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]543pub enum CreateItemExData<CrossAccountId> {544 NFT(545 #[derivative(Debug(format_with = "bounded::vec_debug"))]546 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,547 ),548 Fungible(549 #[derivative(Debug(format_with = "bounded::map_debug"))]550 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,551 ),552 553 RefungibleMultipleItems(554 #[derivative(Debug(format_with = "bounded::vec_debug"))]555 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,556 ),557 558 RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),559}560561impl CreateItemData {562 pub fn data_size(&self) -> usize {563 match self {564 CreateItemData::ReFungible(data) => data.const_data.len(),565 _ => 0,566 }567 }568}569570impl From<CreateNftData> for CreateItemData {571 fn from(item: CreateNftData) -> Self {572 CreateItemData::NFT(item)573 }574}575576impl From<CreateReFungibleData> for CreateItemData {577 fn from(item: CreateReFungibleData) -> Self {578 CreateItemData::ReFungible(item)579 }580}581582impl From<CreateFungibleData> for CreateItemData {583 fn from(item: CreateFungibleData) -> Self {584 CreateItemData::Fungible(item)585 }586}587588#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]589#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]590591pub struct TokenChild {592 pub token: TokenId,593 pub collection: CollectionId,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 contains_key(&self, key: &PropertyKey) -> bool {772 self.0.contains_key(key)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> IntoIterator for PropertiesMap<Value> {793 type Item = (PropertyKey, Value);794 type IntoIter = <795 BoundedBTreeMap<796 PropertyKey,797 Value,798 ConstU32<MAX_PROPERTIES_PER_ITEM>799 > as IntoIterator800 >::IntoIter;801802 fn into_iter(self) -> Self::IntoIter {803 self.0.into_iter()804 }805}806807impl<Value> TrySetProperty for PropertiesMap<Value> {808 type Value = Value;809810 fn try_scoped_set(811 &mut self,812 scope: PropertyScope,813 key: PropertyKey,814 value: Self::Value,815 ) -> Result<(), PropertiesError> {816 Self::check_property_key(&key)?;817818 let key = scope.apply(key)?;819 self.0820 .try_insert(key, value)821 .map_err(|_| PropertiesError::PropertyLimitReached)?;822823 Ok(())824 }825}826827pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;828829#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]830pub struct Properties {831 map: PropertiesMap<PropertyValue>,832 consumed_space: u32,833 space_limit: u32,834}835836impl Properties {837 pub fn new(space_limit: u32) -> Self {838 Self {839 map: PropertiesMap::new(),840 consumed_space: 0,841 space_limit,842 }843 }844845 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {846 let value = self.map.remove(key)?;847848 if let Some(ref value) = value {849 let value_len = value.len() as u32;850 self.consumed_space -= value_len;851 }852853 Ok(value)854 }855856 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {857 self.map.get(key)858 }859}860861impl IntoIterator for Properties {862 type Item = (PropertyKey, PropertyValue);863 type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;864865 fn into_iter(self) -> Self::IntoIter {866 self.map.into_iter()867 }868}869870impl TrySetProperty for Properties {871 type Value = PropertyValue;872873 fn try_scoped_set(874 &mut self,875 scope: PropertyScope,876 key: PropertyKey,877 value: Self::Value,878 ) -> Result<(), PropertiesError> {879 let value_len = value.len();880881 if self.consumed_space as usize + value_len > self.space_limit as usize882 && !cfg!(feature = "runtime-benchmarks")883 {884 return Err(PropertiesError::NoSpaceForProperty);885 }886887 self.map.try_scoped_set(scope, key, value)?;888889 self.consumed_space += value_len as u32;890891 Ok(())892 }893}894895pub struct CollectionProperties;896897impl Get<Properties> for CollectionProperties {898 fn get() -> Properties {899 Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)900 }901}902903pub struct TokenProperties;904905impl Get<Properties> for TokenProperties {906 fn get() -> Properties {907 Properties::new(MAX_TOKEN_PROPERTIES_SIZE)908 }909}910911912913parameter_types! {914 #[derive(PartialEq, TypeInfo)]915 pub const RmrkStringLimit: u32 = 128;916 #[derive(PartialEq)]917 pub const RmrkCollectionSymbolLimit: u32 = 100;918 #[derive(PartialEq)]919 pub const RmrkResourceSymbolLimit: u32 = 10;920 #[derive(PartialEq)]921 pub const RmrkKeyLimit: u32 = 32;922 #[derive(PartialEq)]923 pub const RmrkValueLimit: u32 = 256;924 #[derive(PartialEq)]925 pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;926 #[derive(PartialEq)]927 pub const RmrkPartsLimit: u32 = 3;928}929930impl From<RmrkCollectionId> for CollectionId {931 fn from(id: RmrkCollectionId) -> Self {932 Self(id)933 }934}935936impl From<RmrkNftId> for TokenId {937 fn from(id: RmrkNftId) -> Self {938 Self(id)939 }940}941942pub type RmrkCollectionInfo<AccountId> =943 CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;944pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;945pub type RmrkResourceInfo = ResourceInfo<RmrkBoundedResource, RmrkString, RmrkBoundedParts>;946pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;947pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;948pub type RmrkPartType =949 PartType<RmrkString, BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>>;950pub type RmrkThemeProperty = ThemeProperty<RmrkString>;951pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;952953pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;954pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;955pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;956957type RmrkBoundedResource = BoundedVec<u8, RmrkResourceSymbolLimit>;958type RmrkBoundedParts = BoundedVec<RmrkPartId, RmrkPartsLimit>;959960pub type RmrkRpcString = Vec<u8>;961pub type RmrkThemeName = RmrkRpcString;962pub type RmrkPropertyKey = RmrkRpcString;963964pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;