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};2728#[cfg(feature = "serde")]29use serde::{Serialize, Deserialize};3031use sp_core::U256;32use sp_runtime::{ArithmeticError, sp_std::prelude::Vec, DispatchError};33use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};34use frame_support::{BoundedVec, traits::ConstU32};35use derivative::Derivative;36use scale_info::TypeInfo;3738mod bounded;39pub mod budget;40pub mod mapping;41mod migration;4243pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;44pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;45pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;4647pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {48 100_00049} else {50 1051};52pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {53 100_00054} else {55 1056};57pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {58 204859} else {60 1061};62pub const COLLECTION_ADMINS_LIMIT: u32 = 5;63pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;64pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {65 1_000_00066} else {67 1068};697071pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;72pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;73pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;7475pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;767778pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;79pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;80pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;8182pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;838485pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;86pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;87pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;8889pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;90pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;91pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;929394pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;95pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;9697pub const MAX_COLLECTION_PROPERTIES_ENCODE_LEN: u32 =98 MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH + MAX_COLLECTION_PROPERTIES_SIZE;99100pub struct MaxPropertiesPermissionsEncodeLen;101102impl Get<u32> for MaxPropertiesPermissionsEncodeLen {103 fn get() -> u32 {104 MAX_PROPERTIES_PER_ITEM * MAX_PROPERTY_KEY_LENGTH105 + <PropertyPermission as MaxEncodedLen>::max_encoded_len() as u32106 }107}108109110111pub const MAX_ITEMS_PER_BATCH: u32 = 200;112113pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;114115#[derive(116 Encode,117 Decode,118 PartialEq,119 Eq,120 PartialOrd,121 Ord,122 Clone,123 Copy,124 Debug,125 Default,126 TypeInfo,127 MaxEncodedLen,128)]129#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]130pub struct CollectionId(pub u32);131impl EncodeLike<u32> for CollectionId {}132impl EncodeLike<CollectionId> for u32 {}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 TokenId(pub u32);150impl EncodeLike<u32> for TokenId {}151impl EncodeLike<TokenId> for u32 {}152153impl TokenId {154 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {155 self.0156 .checked_add(1)157 .ok_or(ArithmeticError::Overflow)158 .map(Self)159 }160}161162impl From<TokenId> for U256 {163 fn from(t: TokenId) -> Self {164 t.0.into()165 }166}167168impl TryFrom<U256> for TokenId {169 type Error = &'static str;170171 fn try_from(value: U256) -> Result<Self, Self::Error> {172 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))173 }174}175176pub struct OverflowError;177impl From<OverflowError> for &'static str {178 fn from(_: OverflowError) -> Self {179 "overflow occured"180 }181}182183pub type DecimalPoints = u8;184185#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]186#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]187pub enum CollectionMode {188 NFT,189 190 Fungible(DecimalPoints),191 ReFungible,192}193194impl CollectionMode {195 pub fn id(&self) -> u8 {196 match self {197 CollectionMode::NFT => 1,198 CollectionMode::Fungible(_) => 2,199 CollectionMode::ReFungible => 3,200 }201 }202}203204pub trait SponsoringResolve<AccountId, Call> {205 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;206}207208#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]209#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]210pub enum AccessMode {211 Normal,212 AllowList,213}214impl Default for AccessMode {215 fn default() -> Self {216 Self::Normal217 }218}219220#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]221#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]222pub enum SchemaVersion {223 ImageURL,224 Unique,225}226impl Default for SchemaVersion {227 fn default() -> Self {228 Self::ImageURL229 }230}231232#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]233#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]234pub struct Ownership<AccountId> {235 pub owner: AccountId,236 pub fraction: u128,237}238239#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]240#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]241pub enum SponsorshipState<AccountId> {242 243 Disabled,244 Unconfirmed(AccountId),245 246 Confirmed(AccountId),247}248249impl<AccountId> SponsorshipState<AccountId> {250 pub fn sponsor(&self) -> Option<&AccountId> {251 match self {252 Self::Confirmed(sponsor) => Some(sponsor),253 _ => None,254 }255 }256257 pub fn pending_sponsor(&self) -> Option<&AccountId> {258 match self {259 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),260 _ => None,261 }262 }263264 pub fn confirmed(&self) -> bool {265 matches!(self, Self::Confirmed(_))266 }267}268269impl<T> Default for SponsorshipState<T> {270 fn default() -> Self {271 Self::Disabled272 }273}274275276#[struct_versioning::versioned(version = 2, upper)]277#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]278pub struct Collection<AccountId> {279 pub owner: AccountId,280 pub mode: CollectionMode,281 pub access: AccessMode,282 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,283 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,284 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,285 pub mint_mode: bool,286287 #[version(..2)]288 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,289290 pub schema_version: SchemaVersion,291 pub sponsorship: SponsorshipState<AccountId>,292293 #[version(..2)]294 pub limits: CollectionLimitsVersion1, 295 #[version(2.., upper(limits.into()))]296 pub limits: CollectionLimitsVersion2,297298 #[version(..2)]299 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,300 #[version(..2)]301 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,302303 pub meta_update_permission: MetaUpdatePermission,304}305306307#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]308#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]309pub struct RpcCollection<AccountId> {310 pub owner: AccountId,311 pub mode: CollectionMode,312 pub access: AccessMode,313 pub name: Vec<u16>,314 pub description: Vec<u16>,315 pub token_prefix: Vec<u8>,316 pub mint_mode: bool,317 pub offchain_schema: Vec<u8>,318 pub schema_version: SchemaVersion,319 pub sponsorship: SponsorshipState<AccountId>,320 pub limits: CollectionLimits,321 pub variable_on_chain_schema: Vec<u8>,322 pub const_on_chain_schema: Vec<u8>,323 pub meta_update_permission: MetaUpdatePermission,324}325326#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]327#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]328pub enum CollectionField {329 VariableOnChainSchema,330 ConstOnChainSchema,331 OffchainSchema,332}333334#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]335#[derivative(Debug, Default(bound = ""))]336pub struct CreateCollectionData<AccountId> {337 #[derivative(Default(value = "CollectionMode::NFT"))]338 pub mode: CollectionMode,339 pub access: Option<AccessMode>,340 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,341 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,342 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,343 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,344 pub schema_version: Option<SchemaVersion>,345 pub pending_sponsor: Option<AccountId>,346 pub limits: Option<CollectionLimits>,347 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,348 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,349 pub meta_update_permission: Option<MetaUpdatePermission>,350 pub token_property_permissions: CollectionPropertiesPermissionsVec,351 pub properties: CollectionPropertiesVec,352}353354pub type CollectionPropertiesPermissionsVec =355 BoundedVec<PropertyKeyPermission, MaxPropertiesPermissionsEncodeLen>;356357pub type CollectionPropertiesVec =358 BoundedVec<Property, ConstU32<MAX_COLLECTION_PROPERTIES_ENCODE_LEN>>;359360#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]361#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]362pub struct NftItemType<AccountId> {363 pub owner: AccountId,364 pub const_data: Vec<u8>,365 pub variable_data: Vec<u8>,366}367368#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]369#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]370pub struct FungibleItemType {371 pub value: u128,372}373374#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]375#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]376pub struct ReFungibleItemType<AccountId> {377 pub owner: Vec<Ownership<AccountId>>,378 pub const_data: Vec<u8>,379 pub variable_data: Vec<u8>,380}381382383#[struct_versioning::versioned(version = 2, upper)]384#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]385#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]386pub struct CollectionLimits {387 pub account_token_ownership_limit: Option<u32>,388 pub sponsored_data_size: Option<u32>,389 390 391 392 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,393 pub token_limit: Option<u32>,394395 396 pub sponsor_transfer_timeout: Option<u32>,397 pub sponsor_approve_timeout: Option<u32>,398 pub owner_can_transfer: Option<bool>,399 pub owner_can_destroy: Option<bool>,400 pub transfers_enabled: Option<bool>,401402 #[version(2.., upper(None))]403 pub nesting_rule: Option<NestingRule>,404}405406impl CollectionLimits {407 pub fn account_token_ownership_limit(&self) -> u32 {408 self.account_token_ownership_limit409 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)410 .min(MAX_TOKEN_OWNERSHIP)411 }412 pub fn sponsored_data_size(&self) -> u32 {413 self.sponsored_data_size414 .unwrap_or(CUSTOM_DATA_LIMIT)415 .min(CUSTOM_DATA_LIMIT)416 }417 pub fn token_limit(&self) -> u32 {418 self.token_limit419 .unwrap_or(COLLECTION_TOKEN_LIMIT)420 .min(COLLECTION_TOKEN_LIMIT)421 }422 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {423 self.sponsor_transfer_timeout424 .unwrap_or(default)425 .min(MAX_SPONSOR_TIMEOUT)426 }427 pub fn sponsor_approve_timeout(&self) -> u32 {428 self.sponsor_approve_timeout429 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)430 .min(MAX_SPONSOR_TIMEOUT)431 }432 pub fn owner_can_transfer(&self) -> bool {433 self.owner_can_transfer.unwrap_or(true)434 }435 pub fn owner_can_destroy(&self) -> bool {436 self.owner_can_destroy.unwrap_or(true)437 }438 pub fn transfers_enabled(&self) -> bool {439 self.transfers_enabled.unwrap_or(true)440 }441 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {442 match self443 .sponsored_data_rate_limit444 .unwrap_or(SponsoringRateLimit::SponsoringDisabled)445 {446 SponsoringRateLimit::SponsoringDisabled => None,447 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),448 }449 }450 pub fn nesting_rule(&self) -> &NestingRule {451 static DEFAULT: NestingRule = NestingRule::Owner;452 self.nesting_rule.as_ref().unwrap_or(&DEFAULT)453 }454}455456#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]457#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]458#[derivative(Debug)]459pub enum NestingRule {460 461 Disabled,462 463 Owner,464 465 OwnerRestricted(466 #[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]467 #[derivative(Debug(format_with = "bounded::set_debug"))]468 BoundedBTreeSet<CollectionId, ConstU32<16>>,469 ),470}471472#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]473#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]474pub enum SponsoringRateLimit {475 SponsoringDisabled,476 Blocks(u32),477}478479#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]480#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]481#[derivative(Debug)]482pub struct CreateNftData {483 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]484 #[derivative(Debug(format_with = "bounded::vec_debug"))]485 pub const_data: BoundedVec<u8, CustomDataLimit>,486 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]487 #[derivative(Debug(format_with = "bounded::vec_debug"))]488 pub variable_data: BoundedVec<u8, CustomDataLimit>,489}490491#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]492#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]493pub struct CreateFungibleData {494 pub value: u128,495}496497#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]498#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]499#[derivative(Debug)]500pub struct CreateReFungibleData {501 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]502 #[derivative(Debug(format_with = "bounded::vec_debug"))]503 pub const_data: BoundedVec<u8, CustomDataLimit>,504 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]505 #[derivative(Debug(format_with = "bounded::vec_debug"))]506 pub variable_data: BoundedVec<u8, CustomDataLimit>,507 pub pieces: u128,508}509510#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]511#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]512pub enum MetaUpdatePermission {513 ItemOwner,514 Admin,515 None,516}517518impl Default for MetaUpdatePermission {519 fn default() -> Self {520 Self::ItemOwner521 }522}523524#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]525#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]526pub enum CreateItemData {527 NFT(CreateNftData),528 Fungible(CreateFungibleData),529 ReFungible(CreateReFungibleData),530}531532#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]533#[derivative(Debug)]534pub struct CreateNftExData<CrossAccountId> {535 #[derivative(Debug(format_with = "bounded::vec_debug"))]536 pub const_data: BoundedVec<u8, CustomDataLimit>,537 #[derivative(Debug(format_with = "bounded::vec_debug"))]538 pub variable_data: BoundedVec<u8, CustomDataLimit>,539 pub owner: CrossAccountId,540}541542#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]543#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]544pub struct CreateRefungibleExData<CrossAccountId> {545 #[derivative(Debug(format_with = "bounded::vec_debug"))]546 pub const_data: BoundedVec<u8, CustomDataLimit>,547 #[derivative(Debug(format_with = "bounded::vec_debug"))]548 pub variable_data: BoundedVec<u8, CustomDataLimit>,549 #[derivative(Debug(format_with = "bounded::map_debug"))]550 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,551}552553#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]554#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]555pub enum CreateItemExData<CrossAccountId> {556 NFT(557 #[derivative(Debug(format_with = "bounded::vec_debug"))]558 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,559 ),560 Fungible(561 #[derivative(Debug(format_with = "bounded::map_debug"))]562 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,563 ),564 565 RefungibleMultipleItems(566 #[derivative(Debug(format_with = "bounded::vec_debug"))]567 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,568 ),569 570 RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),571}572573impl CreateItemData {574 pub fn data_size(&self) -> usize {575 match self {576 CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),577 CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),578 _ => 0,579 }580 }581}582583impl From<CreateNftData> for CreateItemData {584 fn from(item: CreateNftData) -> Self {585 CreateItemData::NFT(item)586 }587}588589impl From<CreateReFungibleData> for CreateItemData {590 fn from(item: CreateReFungibleData) -> Self {591 CreateItemData::ReFungible(item)592 }593}594595impl From<CreateFungibleData> for CreateItemData {596 fn from(item: CreateFungibleData) -> Self {597 CreateItemData::Fungible(item)598 }599}600601#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]602#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]603pub struct CollectionStats {604 pub created: u32,605 pub destroyed: u32,606 pub alive: u32,607}608609#[derive(Encode, Decode, PartialEq, Clone, Debug)]610pub struct PhantomType<T>(core::marker::PhantomData<T>);611612impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {613 type Identity = PhantomType<T>;614615 fn type_info() -> scale_info::Type {616 use scale_info::{617 Type, Path,618 build::{FieldsBuilder, UnnamedFields},619 type_params,620 };621 Type::builder()622 .path(Path::new("up_data_structs", "PhantomType"))623 .type_params(type_params!(T))624 .composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))625 }626}627impl<T> MaxEncodedLen for PhantomType<T> {628 fn max_encoded_len() -> usize {629 0630 }631}632633pub type PropertyKey = BoundedVec<u8, ConstU32<MAX_PROPERTY_KEY_LENGTH>>;634pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;635636#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]637#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]638pub enum PropertyPermission {639 None,640 AdminConst,641 Admin,642 ItemOwnerConst,643 ItemOwner,644 ItemOwnerOrAdmin,645}646647#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]648#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]649pub struct Property {650 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]651 pub key: PropertyKey,652653 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]654 pub value: PropertyValue,655}656657#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]658#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]659pub struct PropertyKeyPermission {660 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]661 pub key: PropertyKey,662663 pub permission: PropertyPermission,664}665666pub enum PropertiesError {667 NoSpaceForProperty,668 PropertyLimitReached,669}670671pub type PropertiesMap =672 BoundedBTreeMap<PropertyKey, PropertyValue, ConstU32<MAX_PROPERTIES_PER_ITEM>>;673pub type PropertiesPermissionMap =674 BoundedBTreeMap<PropertyKey, PropertyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;675676#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]677pub struct Properties {678 map: PropertiesMap,679 consumed_space: u32,680 space_limit: u32,681}682683impl Properties {684 pub fn new(space_limit: u32) -> Self {685 Self {686 map: BoundedBTreeMap::new(),687 consumed_space: 0,688 space_limit,689 }690 }691692 pub fn from_collection_props_vec(693 data: CollectionPropertiesVec,694 ) -> Result<Self, PropertiesError> {695 let mut props = Self::new(MAX_COLLECTION_PROPERTIES_SIZE);696697 for property in data.into_iter() {698 props.try_set_property(property)?;699 }700701 Ok(props)702 }703704 pub fn try_set_property(&mut self, property: Property) -> Result<(), PropertiesError> {705 let value_len = property.value.len();706707 if self.consumed_space as usize + value_len > self.space_limit as usize {708 return Err(PropertiesError::NoSpaceForProperty);709 }710711 self.map712 .try_insert(property.key, property.value)713 .map_err(|_| PropertiesError::PropertyLimitReached)?;714715 self.consumed_space += value_len as u32;716717 Ok(())718 }719720 pub fn remove_property(&mut self, key: &PropertyKey) {721 let property = self.map.get(key);722723 if let Some(value) = property {724 let value_len = value.len() as u32;725726 self.map.remove(key);727 self.consumed_space -= value_len;728 }729 }730731 pub fn get_property(&self, key: &PropertyKey) -> Option<&PropertyValue> {732 self.map.get(key)733 }734735 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {736 self.map.iter()737 }738}739740pub struct CollectionProperties;741742impl Get<Properties> for CollectionProperties {743 fn get() -> Properties {744 Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)745 }746}747748pub struct TokenProperties;749750impl Get<Properties> for TokenProperties {751 fn get() -> Properties {752 Properties::new(MAX_TOKEN_PROPERTIES_SIZE)753 }754}