difftreelog
fix rmrk_property macro
in: master
2 files changed
pallets/rmrk-proxy/src/misc.rsdiffbeforeafterboth--- a/pallets/rmrk-proxy/src/misc.rs
+++ b/pallets/rmrk-proxy/src/misc.rs
@@ -1,19 +1,24 @@
use super::*;
use codec::{Encode, Decode};
+use frame_support::dispatch::Vec;
use pallet_nonfungible::NonfungibleHandle;
#[macro_export]
macro_rules! rmrk_property {
($key:ident, $value:expr) => {
Property {
- key: rmrk_property!($key),
+ key: rmrk_property!(@raw $key),
value: $value.into()
}
};
- ($key:ident) => {
+ (@raw $key:ident) => {
RmrkProperty::$key.to_key()
};
+
+ ($key:ident) => {
+ PropertyScope::Rmrk.apply(rmrk_property!(@raw $key)).unwrap()
+ };
}
macro_rules! impl_rmrk_value {
primitives/data-structs/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![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;3839// RMRK40use 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};8283// Timeouts for item types in passed blocks84pub 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;8990// Schema limits91pub 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;104105// pub const MAX_PROPERTY_KEYS_OVERALL_LENGTH: u32 = MAX_PROPERTY_KEY_LENGTH * MAX_PROPERTIES_PER_ITEM;106pub 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;111112// RMRK constants113pub 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}127128/// How much items can be created per single129/// create_many call130pub 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 // decimal points217 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 /// The fees are applied to the transaction sender270 Disabled,271 Unconfirmed(AccountId),272 /// Transactions are sponsored by specified account273 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}301302/// Used in storage303#[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, // Collection private restrictions322 #[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}334335/// Used in RPC calls336#[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>>;385386/// All fields are wrapped in `Option`s, where None means chain default387#[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 /// FIXME should we delete this or repurpose it?395 /// None - setVariableMetadata is not sponsored396 /// Some(v) - setVariableMetadata is sponsored397 /// if there is v block between txs398 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,399 pub token_limit: Option<u32>,400401 // Timeouts for item types in passed blocks402 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 /// No one can nest tokens467 Disabled,468 /// Owner can nest any tokens469 Owner,470 /// Owner can nest tokens from specified collections471 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 /// Many tokens, each may have only one owner560 RefungibleMultipleItems(561 #[derivative(Debug(format_with = "bounded::vec_debug"))]562 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,563 ),564 /// Single token, which may have many owners565 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}680681pub enum PropertiesError {682 NoSpaceForProperty,683 PropertyLimitReached,684 InvalidCharacterInPropertyKey,685 PropertyKeyIsTooLong,686 EmptyPropertyKey,687}688689#[derive(Clone, Copy)]690pub enum PropertyScope {691 None,692 Rmrk,693}694695impl PropertyScope {696 fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {697 let scope_str: &[u8] = match self {698 Self::None => return Ok(key),699 Self::Rmrk => b"rmrk",700 };701702 [scope_str, b":", key.as_slice()]703 .concat()704 .try_into()705 .map_err(|_| PropertiesError::PropertyKeyIsTooLong)706 }707}708709pub trait TrySetProperty: Sized {710 type Value;711712 fn try_scoped_set(713 &mut self,714 scope: PropertyScope,715 key: PropertyKey,716 value: Self::Value,717 ) -> Result<(), PropertiesError>;718719 fn try_scoped_set_from_iter<I, KV>(720 &mut self,721 scope: PropertyScope,722 iter: I,723 ) -> Result<(), PropertiesError>724 where725 I: Iterator<Item=KV>,726 KV: Into<(PropertyKey, Self::Value)>727 {728 for kv in iter {729 let (key, value) = kv.into();730 self.try_scoped_set(scope, key, value)?;731 }732733 Ok(())734 }735736 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {737 self.try_scoped_set(PropertyScope::None, key, value)738 }739740 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>741 where742 I: Iterator<Item=KV>,743 KV: Into<(PropertyKey, Self::Value)>744 {745 self.try_scoped_set_from_iter(PropertyScope::None, iter)746 }747}748749#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]750#[derivative(Default(bound = ""))]751pub struct PropertiesMap<Value>(752 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,753);754755impl<Value> PropertiesMap<Value> {756 pub fn new() -> Self {757 Self(BoundedBTreeMap::new())758 }759760 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {761 Self::check_property_key(key)?;762763 Ok(self.0.remove(key))764 }765766 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {767 self.0.get(key)768 }769770 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &Value)> {771 self.0.iter()772 }773774 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {775 if key.is_empty() {776 return Err(PropertiesError::EmptyPropertyKey);777 }778779 for byte in key.as_slice().iter() {780 let byte = *byte;781782 if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' {783 return Err(PropertiesError::InvalidCharacterInPropertyKey);784 }785 }786787 Ok(())788 }789}790791impl<Value> TrySetProperty for PropertiesMap<Value> {792 type Value = Value;793794 fn try_scoped_set(795 &mut self,796 scope: PropertyScope,797 key: PropertyKey,798 value: Self::Value,799 ) -> Result<(), PropertiesError> {800 Self::check_property_key(&key)?;801802 let key = scope.apply(key)?;803 self.0804 .try_insert(key, value)805 .map_err(|_| PropertiesError::PropertyLimitReached)?;806807 Ok(())808 }809}810811pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;812813#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]814pub struct Properties {815 map: PropertiesMap<PropertyValue>,816 consumed_space: u32,817 space_limit: u32,818}819820impl Properties {821 pub fn new(space_limit: u32) -> Self {822 Self {823 map: PropertiesMap::new(),824 consumed_space: 0,825 space_limit,826 }827 }828829 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {830 let value = self.map.remove(key)?;831832 if let Some(ref value) = value {833 let value_len = value.len() as u32;834 self.consumed_space -= value_len;835 }836837 Ok(value)838 }839840 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {841 self.map.get(key)842 }843844 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {845 self.map.iter()846 }847}848849impl TrySetProperty for Properties {850 type Value = PropertyValue;851852 fn try_scoped_set(853 &mut self,854 scope: PropertyScope,855 key: PropertyKey,856 value: Self::Value,857 ) -> Result<(), PropertiesError> {858 let value_len = value.len();859860 if self.consumed_space as usize + value_len > self.space_limit as usize {861 return Err(PropertiesError::NoSpaceForProperty);862 }863864 self.map.try_scoped_set(scope, key, value)?;865866 self.consumed_space += value_len as u32;867868 Ok(())869 }870}871872pub struct CollectionProperties;873874impl Get<Properties> for CollectionProperties {875 fn get() -> Properties {876 Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)877 }878}879880pub struct TokenProperties;881882impl Get<Properties> for TokenProperties {883 fn get() -> Properties {884 Properties::new(MAX_TOKEN_PROPERTIES_SIZE)885 }886}887888// RMRK889// todo document?890parameter_types! {891 #[derive(PartialEq, TypeInfo)]892 pub const RmrkStringLimit: u32 = 128;893 #[derive(PartialEq)]894 pub const RmrkCollectionSymbolLimit: u32 = 100;895 #[derive(PartialEq)]896 pub const RmrkResourceSymbolLimit: u32 = 10;897 #[derive(PartialEq)]898 pub const RmrkKeyLimit: u32 = 32;899 #[derive(PartialEq)]900 pub const RmrkValueLimit: u32 = 256;901 #[derive(PartialEq)]902 pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;903 #[derive(PartialEq)]904 pub const RmrkPartsLimit: u32 = 3;905}906907pub type RmrkCollectionInfo<AccountId> =908 CollectionInfo<RmrkString, BoundedVec<u8, RmrkCollectionSymbolLimit>, AccountId>;909pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;910pub type RmrkResourceInfo = ResourceInfo<911 BoundedVec<u8, RmrkResourceSymbolLimit>,912 RmrkString,913 BoundedVec<RmrkPartId, RmrkPartsLimit>,914>;915pub type RmrkPropertyInfo =916 PropertyInfo<BoundedVec<u8, RmrkKeyLimit>, BoundedVec<u8, RmrkValueLimit>>;917pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;918pub type RmrkPartType =919 PartType<RmrkString, BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>>;920pub type RmrkTheme = Theme<RmrkString, Vec<ThemeProperty<RmrkString>>>;921922pub type RmrkRpcString = Vec<u8>;923pub type RmrkThemeName = RmrkRpcString;924pub type RmrkPropertyKey = RmrkRpcString;925926type RmrkString = BoundedVec<u8, RmrkStringLimit>;1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![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;3839// RMRK40use 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};8283// Timeouts for item types in passed blocks84pub 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;8990// Schema limits91pub 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;104105// pub const MAX_PROPERTY_KEYS_OVERALL_LENGTH: u32 = MAX_PROPERTY_KEY_LENGTH * MAX_PROPERTIES_PER_ITEM;106pub 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;111112// RMRK constants113pub 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}127128/// How much items can be created per single129/// create_many call130pub 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 // decimal points217 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 /// The fees are applied to the transaction sender270 Disabled,271 Unconfirmed(AccountId),272 /// Transactions are sponsored by specified account273 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}301302/// Used in storage303#[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, // Collection private restrictions322 #[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}334335/// Used in RPC calls336#[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>>;385386/// All fields are wrapped in `Option`s, where None means chain default387#[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 /// FIXME should we delete this or repurpose it?395 /// None - setVariableMetadata is not sponsored396 /// Some(v) - setVariableMetadata is sponsored397 /// if there is v block between txs398 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,399 pub token_limit: Option<u32>,400401 // Timeouts for item types in passed blocks402 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 /// No one can nest tokens467 Disabled,468 /// Owner can nest any tokens469 Owner,470 /// Owner can nest tokens from specified collections471 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 /// Many tokens, each may have only one owner560 RefungibleMultipleItems(561 #[derivative(Debug(format_with = "bounded::vec_debug"))]562 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,563 ),564 /// Single token, which may have many owners565 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}888889// RMRK890// todo document?891parameter_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}907908pub type RmrkCollectionInfo<AccountId> =909 CollectionInfo<RmrkString, BoundedVec<u8, RmrkCollectionSymbolLimit>, AccountId>;910pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;911pub type RmrkResourceInfo = ResourceInfo<912 BoundedVec<u8, RmrkResourceSymbolLimit>,913 RmrkString,914 BoundedVec<RmrkPartId, RmrkPartsLimit>,915>;916pub type RmrkPropertyInfo =917 PropertyInfo<BoundedVec<u8, RmrkKeyLimit>, BoundedVec<u8, RmrkValueLimit>>;918pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;919pub type RmrkPartType =920 PartType<RmrkString, BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>>;921pub type RmrkTheme = Theme<RmrkString, Vec<ThemeProperty<RmrkString>>>;922923pub type RmrkRpcString = Vec<u8>;924pub type RmrkThemeName = RmrkRpcString;925pub type RmrkPropertyKey = RmrkRpcString;926927type RmrkString = BoundedVec<u8, RmrkStringLimit>;