difftreelog
fix PR
in: master
4 files changed
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -90,6 +90,7 @@
/// @notice Set permissions for token property.
/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
/// @param permissions Permissions for keys.
+ #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]
fn set_token_property_permissions(
&mut self,
caller: caller,
@@ -98,7 +99,7 @@
let caller = T::CrossAccountId::from_eth(caller);
const PERMISSIONS_FIELDS_COUNT: usize = 3;
- let mut perms = <Vec<_>>::new();
+ let mut perms = Vec::new();
for (key, pp) in permissions {
if pp.len() > PERMISSIONS_FIELDS_COUNT {
@@ -112,11 +113,7 @@
.into());
}
- let mut token_permission = PropertyPermission {
- mutable: false,
- collection_admin: false,
- token_owner: false,
- };
+ let mut token_permission = PropertyPermission::default();
for (perm, value) in pp {
match perm {
@@ -129,9 +126,7 @@
}
perms.push(PropertyKeyPermission {
- key: <Vec<u8>>::from(key)
- .try_into()
- .map_err(|_| "too long key")?,
+ key: key.into_bytes().try_into().map_err(|_| "too long key")?,
permission: token_permission,
});
}
@@ -144,17 +139,19 @@
fn token_property_permissions(
&self,
) -> Result<Vec<(string, Vec<(EthTokenPermissions, bool)>)>> {
- let mut res = <Vec<_>>::new();
- for (key, pp) in <Pallet<T>>::token_property_permission(self.id) {
- let key = string::from_utf8(key.into_inner()).unwrap();
- let pp = vec![
- (EthTokenPermissions::Mutable, pp.mutable),
- (EthTokenPermissions::TokenOwner, pp.token_owner),
- (EthTokenPermissions::CollectionAdmin, pp.collection_admin),
- ];
- res.push((key, pp));
- }
- Ok(res)
+ let perms = <Pallet<T>>::token_property_permission(self.id);
+ Ok(perms
+ .into_iter()
+ .map(|(key, pp)| {
+ let key = string::from_utf8(key.into_inner()).expect("Stored key must be valid");
+ let pp = vec![
+ (EthTokenPermissions::Mutable, pp.mutable),
+ (EthTokenPermissions::TokenOwner, pp.token_owner),
+ (EthTokenPermissions::CollectionAdmin, pp.collection_admin),
+ ];
+ (key, pp)
+ })
+ .collect())
}
/// @notice Set token property value.
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -93,6 +93,7 @@
/// @notice Set permissions for token property.
/// @dev Throws error if `msg.sender` is not admin or owner of the collection.
/// @param permissions Permissions for keys.
+ #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]
fn set_token_property_permissions(
&mut self,
caller: caller,
@@ -101,7 +102,7 @@
let caller = T::CrossAccountId::from_eth(caller);
const PERMISSIONS_FIELDS_COUNT: usize = 3;
- let mut perms = <Vec<_>>::new();
+ let mut perms = Vec::new();
for (key, pp) in permissions {
if pp.len() > PERMISSIONS_FIELDS_COUNT {
@@ -132,9 +133,7 @@
}
perms.push(PropertyKeyPermission {
- key: <Vec<u8>>::from(key)
- .try_into()
- .map_err(|_| "too long key")?,
+ key: key.into_bytes().try_into().map_err(|_| "too long key")?,
permission: token_permission,
});
}
@@ -147,18 +146,19 @@
fn token_property_permissions(
&self,
) -> Result<Vec<(string, Vec<(EthTokenPermissions, bool)>)>> {
- let mut res = <Vec<_>>::new();
- for (key, pp) in <Pallet<T>>::token_property_permission(self.id) {
- let key = string::from_utf8(key.into_inner()).unwrap();
- let pp = [
- (EthTokenPermissions::Mutable, pp.mutable),
- (EthTokenPermissions::TokenOwner, pp.token_owner),
- (EthTokenPermissions::CollectionAdmin, pp.collection_admin),
- ]
- .into();
- res.push((key, pp));
- }
- Ok(res)
+ let perms = <Pallet<T>>::token_property_permission(self.id);
+ Ok(perms
+ .into_iter()
+ .map(|(key, pp)| {
+ let key = string::from_utf8(key.into_inner()).expect("Stored key must be valid");
+ let pp = vec![
+ (EthTokenPermissions::Mutable, pp.mutable),
+ (EthTokenPermissions::TokenOwner, pp.token_owner),
+ (EthTokenPermissions::CollectionAdmin, pp.collection_admin),
+ ];
+ (key, pp)
+ })
+ .collect())
}
/// @notice Set token property 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//! # Primitives crate.18//!19//! This crate contains types, traits and constants.2021#![cfg_attr(not(feature = "std"), no_std)]2223use core::{24 convert::{TryFrom, TryInto},25 fmt,26};27use frame_support::{28 storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},29 traits::Get,30 parameter_types,31};3233#[cfg(feature = "serde")]34use serde::{Serialize, Deserialize};3536use sp_core::U256;37use sp_runtime::{ArithmeticError, sp_std::prelude::Vec, Permill};38use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};39use bondrewd::Bitfields;40use frame_support::{BoundedVec, traits::ConstU32};41use derivative::Derivative;42use scale_info::TypeInfo;4344// RMRK45use rmrk_traits::{46 CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme, ThemeProperty,47 ResourceTypes, BasicResource, ComposableResource, SlotResource, EquippableList,48};49pub use rmrk_traits::{50 primitives::{51 CollectionId as RmrkCollectionId, NftId as RmrkNftId, BaseId as RmrkBaseId,52 SlotId as RmrkSlotId, PartId as RmrkPartId, ResourceId as RmrkResourceId,53 },54 NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,55 FixedPart as RmrkFixedPart, SlotPart as RmrkSlotPart,56};5758mod bondrewd_codec;59mod bounded;60pub mod budget;61pub mod mapping;62mod migration;6364/// Maximum of decimal points.65pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;6667/// Maximum pieces for refungible token.68pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;69pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;7071/// Maximum tokens for user.72pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {73 100_00074} else {75 1076};7778/// Maximum for collections can be created.79pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {80 100_00081} else {82 1083};8485/// Maximum for various custom data of token.86pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {87 204888} else {89 1090};9192/// Maximum admins per collection.93pub const COLLECTION_ADMINS_LIMIT: u32 = 5;9495/// Maximum tokens per collection.96pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;9798/// Maximum tokens per account.99pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {100 1_000_000101} else {102 10103};104105/// Default timeout for transfer sponsoring NFT item.106pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;107/// Default timeout for transfer sponsoring fungible item.108pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;109/// Default timeout for transfer sponsoring refungible item.110pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;111112/// Default timeout for sponsored approving.113pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;114115// Schema limits116pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;117pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;118pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;119120// TODO: not used. Delete?121pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;122123/// Maximal length of a collection name.124pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;125126/// Maximal length of a collection description.127pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;128129/// Maximal length of a token prefix.130pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;131132/// Maximal length of a property key.133pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;134135/// Maximal length of a property value.136pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;137138/// A maximum number of token properties.139pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;140141/// Maximal lenght of extended property value.142pub const MAX_AUX_PROPERTY_VALUE_LENGTH: u32 = 2048;143144/// Maximum size for all collection properties.145pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;146147/// Maximum size of all token properties.148pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;149150/// How much items can be created per single151/// create_many call.152pub const MAX_ITEMS_PER_BATCH: u32 = 200;153154/// Used for limit bounded types of token custom data.155pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;156157/// Collection id.158#[derive(159 Encode,160 Decode,161 PartialEq,162 Eq,163 PartialOrd,164 Ord,165 Clone,166 Copy,167 Debug,168 Default,169 TypeInfo,170 MaxEncodedLen,171)]172#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]173pub struct CollectionId(pub u32);174impl EncodeLike<u32> for CollectionId {}175impl EncodeLike<CollectionId> for u32 {}176177/// Token id.178#[derive(179 Encode,180 Decode,181 PartialEq,182 Eq,183 PartialOrd,184 Ord,185 Clone,186 Copy,187 Debug,188 Default,189 TypeInfo,190 MaxEncodedLen,191)]192#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]193pub struct TokenId(pub u32);194impl EncodeLike<u32> for TokenId {}195impl EncodeLike<TokenId> for u32 {}196197impl TokenId {198 /// Try to get next token id.199 ///200 /// If next id cause overflow, then [`ArithmeticError::Overflow`] returned.201 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {202 self.0203 .checked_add(1)204 .ok_or(ArithmeticError::Overflow)205 .map(Self)206 }207}208209impl From<TokenId> for U256 {210 fn from(t: TokenId) -> Self {211 t.0.into()212 }213}214215impl TryFrom<U256> for TokenId {216 type Error = &'static str;217218 fn try_from(value: U256) -> Result<Self, Self::Error> {219 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))220 }221}222223/// Token data.224#[struct_versioning::versioned(version = 2, upper)]225#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]226#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]227pub struct TokenData<CrossAccountId> {228 /// Properties of token.229 pub properties: Vec<Property>,230231 /// Token owner.232 pub owner: Option<CrossAccountId>,233234 /// Token pieces.235 #[version(2.., upper(0))]236 pub pieces: u128,237}238239// TODO: unused type240pub struct OverflowError;241impl From<OverflowError> for &'static str {242 fn from(_: OverflowError) -> Self {243 "overflow occured"244 }245}246247/// Alias for decimal points type.248pub type DecimalPoints = u8;249250/// Collection mode.251///252/// Collection can represent various types of tokens.253/// Each collection can contain only one type of tokens at a time.254/// This type helps to understand which tokens the collection contains.255#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]256#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]257pub enum CollectionMode {258 /// Non fungible tokens.259 NFT,260 /// Fungible tokens.261 Fungible(DecimalPoints),262 /// Refungible tokens.263 ReFungible,264}265266impl CollectionMode {267 /// Get collection mod as number.268 pub fn id(&self) -> u8 {269 match self {270 CollectionMode::NFT => 1,271 CollectionMode::Fungible(_) => 2,272 CollectionMode::ReFungible => 3,273 }274 }275}276277// TODO: unused trait278pub trait SponsoringResolve<AccountId, Call> {279 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;280}281282/// Access mode for some token operations.283#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]284#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]285pub enum AccessMode {286 /// Access grant for owner and admins. Used as default.287 Normal,288 /// Like a [`Normal`](AccessMode::Normal) but also users in allow list.289 AllowList,290}291impl Default for AccessMode {292 fn default() -> Self {293 Self::Normal294 }295}296297// TODO: remove in future.298#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]299#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]300pub enum SchemaVersion {301 ImageURL,302 Unique,303}304impl Default for SchemaVersion {305 fn default() -> Self {306 Self::ImageURL307 }308}309310// TODO: unused type311#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]312#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]313pub struct Ownership<AccountId> {314 pub owner: AccountId,315 pub fraction: u128,316}317318/// The state of collection sponsorship.319#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]320#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]321pub enum SponsorshipState<AccountId> {322 /// The fees are applied to the transaction sender.323 Disabled,324 /// The sponsor is under consideration. Until the sponsor gives his consent,325 /// the fee will still be charged to sender.326 Unconfirmed(AccountId),327 /// Transactions are sponsored by specified account.328 Confirmed(AccountId),329}330331impl<AccountId> SponsorshipState<AccountId> {332 /// Get a sponsor of the collection who has confirmed his status.333 pub fn sponsor(&self) -> Option<&AccountId> {334 match self {335 Self::Confirmed(sponsor) => Some(sponsor),336 _ => None,337 }338 }339340 /// Get a sponsor of the collection who has pending or confirmed status.341 pub fn pending_sponsor(&self) -> Option<&AccountId> {342 match self {343 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),344 _ => None,345 }346 }347348 /// Whether the sponsorship is confirmed.349 pub fn confirmed(&self) -> bool {350 matches!(self, Self::Confirmed(_))351 }352}353354impl<T> Default for SponsorshipState<T> {355 fn default() -> Self {356 Self::Disabled357 }358}359360pub type CollectionName = BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>;361pub type CollectionDescription = BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>;362pub type CollectionTokenPrefix = BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>;363364#[derive(Bitfields, Clone, Copy, PartialEq, Eq, Debug, Default)]365#[bondrewd(enforce_bytes = 1)]366pub struct CollectionFlags {367 /// Tokens in foreign collections can be transferred, but not burnt368 #[bondrewd(bits = "0..1")]369 pub foreign: bool,370 /// Supports ERC721Metadata371 #[bondrewd(bits = "1..2")]372 pub erc721metadata: bool,373 /// External collections can't be managed using `unique` api374 #[bondrewd(bits = "7..8")]375 pub external: bool,376377 #[bondrewd(reserve, bits = "2..7")]378 pub reserved: u8,379}380bondrewd_codec!(CollectionFlags);381382/// Base structure for represent collection.383///384/// Used to provide basic functionality for all types of collections.385///386/// #### Note387/// Collection parameters, used in storage (see [`RpcCollection`] for the RPC version).388#[struct_versioning::versioned(version = 2, upper)]389#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]390pub struct Collection<AccountId> {391 /// Collection owner account.392 pub owner: AccountId,393394 /// Collection mode.395 pub mode: CollectionMode,396397 /// Access mode.398 #[version(..2)]399 pub access: AccessMode,400401 /// Collection name.402 pub name: CollectionName,403404 /// Collection description.405 pub description: CollectionDescription,406407 /// Token prefix.408 pub token_prefix: CollectionTokenPrefix,409410 #[version(..2)]411 pub mint_mode: bool,412413 #[version(..2)]414 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,415416 #[version(..2)]417 pub schema_version: SchemaVersion,418419 /// The state of sponsorship of the collection.420 pub sponsorship: SponsorshipState<AccountId>,421422 /// Collection limits.423 pub limits: CollectionLimits,424425 /// Collection permissions.426 #[version(2.., upper(Default::default()))]427 pub permissions: CollectionPermissions,428429 #[version(2.., upper(Default::default()))]430 pub flags: CollectionFlags,431432 #[version(..2)]433 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,434435 #[version(..2)]436 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,437438 #[version(..2)]439 pub meta_update_permission: MetaUpdatePermission,440}441442#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]443#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]444pub struct RpcCollectionFlags {445 /// Is collection is foreign.446 pub foreign: bool,447 /// Collection supports ERC721Metadata.448 pub erc721metadata: bool,449}450451/// Collection parameters, used in RPC calls (see [`Collection`] for the storage version).452#[struct_versioning::versioned(version = 2, upper)]453#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]454#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]455pub struct RpcCollection<AccountId> {456 /// Collection owner account.457 pub owner: AccountId,458459 /// Collection mode.460 pub mode: CollectionMode,461462 /// Collection name.463 pub name: Vec<u16>,464465 /// Collection description.466 pub description: Vec<u16>,467468 /// Token prefix.469 pub token_prefix: Vec<u8>,470471 /// The state of sponsorship of the collection.472 pub sponsorship: SponsorshipState<AccountId>,473474 /// Collection limits.475 pub limits: CollectionLimits,476477 /// Collection permissions.478 pub permissions: CollectionPermissions,479480 /// Token property permissions.481 pub token_property_permissions: Vec<PropertyKeyPermission>,482483 /// Collection properties.484 pub properties: Vec<Property>,485486 /// Is collection read only.487 pub read_only: bool,488489 /// Extra collection flags490 #[version(2.., upper(RpcCollectionFlags {foreign: false, erc721metadata: false}))]491 pub flags: RpcCollectionFlags,492}493494/// Data used for create collection.495///496/// All fields are wrapped in [`Option`], where `None` means chain default.497#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]498#[derivative(Debug, Default(bound = ""))]499pub struct CreateCollectionData<AccountId> {500 /// Collection mode.501 #[derivative(Default(value = "CollectionMode::NFT"))]502 pub mode: CollectionMode,503504 /// Access mode.505 pub access: Option<AccessMode>,506507 /// Collection name.508 pub name: CollectionName,509510 /// Collection description.511 pub description: CollectionDescription,512513 /// Token prefix.514 pub token_prefix: CollectionTokenPrefix,515516 /// Pending collection sponsor.517 pub pending_sponsor: Option<AccountId>,518519 /// Collection limits.520 pub limits: Option<CollectionLimits>,521522 /// Collection permissions.523 pub permissions: Option<CollectionPermissions>,524525 /// Token property permissions.526 pub token_property_permissions: CollectionPropertiesPermissionsVec,527528 /// Collection properties.529 pub properties: CollectionPropertiesVec,530}531532/// Bounded vector of properties permissions. Max length is [`MAX_PROPERTIES_PER_ITEM`].533// TODO: maybe rename to PropertiesPermissionsVec534pub type CollectionPropertiesPermissionsVec =535 BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;536537/// Bounded vector of properties. Max length is [`MAX_PROPERTIES_PER_ITEM`].538pub type CollectionPropertiesVec = BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;539540/// Limits and restrictions of a collection.541///542/// All fields are wrapped in [`Option`], where `None` means chain default.543///544/// Update with `pallet_common::Pallet::clamp_limits`.545// IMPORTANT: When adding/removing fields from this struct - don't forget to also546#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]547#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]548// When adding/removing fields from this struct - don't forget to also update with `pallet_common::Pallet::clamp_limits`.549// TODO: move `pallet_common::Pallet::clamp_limits` into `impl CollectionLimits`.550// TODO: may be remove [`Option`] and **pub** from fields and create struct with default values.551pub struct CollectionLimits {552 /// How many tokens can a user have on one account.553 /// * Default - [`ACCOUNT_TOKEN_OWNERSHIP_LIMIT`].554 /// * Limit - [`MAX_TOKEN_OWNERSHIP`].555 pub account_token_ownership_limit: Option<u32>,556557 /// How many bytes of data are available for sponsorship.558 /// * Default - [`CUSTOM_DATA_LIMIT`].559 /// * Limit - [`CUSTOM_DATA_LIMIT`].560 pub sponsored_data_size: Option<u32>,561562 // FIXME should we delete this or repurpose it?563 /// Times in how many blocks we sponsor data.564 ///565 /// If is `Some(v)` then **setVariableMetadata** is sponsored if there is `v` block between transactions.566 ///567 /// * Default - [`SponsoringDisabled`](SponsoringRateLimit::SponsoringDisabled).568 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].569 ///570 /// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]571 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,572 /// Maximum amount of tokens inside the collection. Chain default: [`COLLECTION_TOKEN_LIMIT`]573574 /// How many tokens can be mined into this collection.575 ///576 /// * Default - [`COLLECTION_TOKEN_LIMIT`].577 /// * Limit - [`COLLECTION_TOKEN_LIMIT`].578 pub token_limit: Option<u32>,579580 /// Timeouts for transfer sponsoring.581 ///582 /// * Default583 /// - **Fungible** - [`FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`]584 /// - **NFT** - [`NFT_SPONSOR_TRANSFER_TIMEOUT`]585 /// - **Refungible** - [`REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`]586 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].587 pub sponsor_transfer_timeout: Option<u32>,588589 /// Timeout for sponsoring an approval in passed blocks.590 ///591 /// * Default - [`SPONSOR_APPROVE_TIMEOUT`].592 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].593 pub sponsor_approve_timeout: Option<u32>,594595 /// Whether the collection owner of the collection can send tokens (which belong to other users).596 ///597 /// * Default - **false**.598 pub owner_can_transfer: Option<bool>,599600 /// Can the collection owner burn other people's tokens.601 ///602 /// * Default - **true**.603 pub owner_can_destroy: Option<bool>,604605 /// Is it possible to send tokens from this collection between users.606 ///607 /// * Default - **true**.608 pub transfers_enabled: Option<bool>,609}610611impl CollectionLimits {612 pub fn with_default_limits(collection_type: CollectionMode) -> Self {613 CollectionLimits {614 account_token_ownership_limit: Some(ACCOUNT_TOKEN_OWNERSHIP_LIMIT),615 sponsored_data_size: Some(CUSTOM_DATA_LIMIT),616 sponsored_data_rate_limit: Some(SponsoringRateLimit::SponsoringDisabled),617 token_limit: Some(COLLECTION_TOKEN_LIMIT),618 sponsor_transfer_timeout: match collection_type {619 CollectionMode::NFT => Some(NFT_SPONSOR_TRANSFER_TIMEOUT),620 CollectionMode::ReFungible => Some(REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT),621 CollectionMode::Fungible(_) => Some(FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT),622 },623 sponsor_approve_timeout: Some(SPONSOR_APPROVE_TIMEOUT),624 owner_can_transfer: Some(false),625 owner_can_destroy: Some(true),626 transfers_enabled: Some(true),627 }628 }629630 /// Get effective value for [`account_token_ownership_limit`](self.account_token_ownership_limit).631 pub fn account_token_ownership_limit(&self) -> u32 {632 self.account_token_ownership_limit633 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)634 .min(MAX_TOKEN_OWNERSHIP)635 }636637 /// Get effective value for [`sponsored_data_size`](self.sponsored_data_size).638 pub fn sponsored_data_size(&self) -> u32 {639 self.sponsored_data_size640 .unwrap_or(CUSTOM_DATA_LIMIT)641 .min(CUSTOM_DATA_LIMIT)642 }643644 /// Get effective value for [`token_limit`](self.token_limit).645 pub fn token_limit(&self) -> u32 {646 self.token_limit647 .unwrap_or(COLLECTION_TOKEN_LIMIT)648 .min(COLLECTION_TOKEN_LIMIT)649 }650651 // TODO: may be replace u32 to mode?652 /// Get effective value for [`sponsor_transfer_timeout`](self.sponsor_transfer_timeout).653 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {654 self.sponsor_transfer_timeout655 .unwrap_or(default)656 .min(MAX_SPONSOR_TIMEOUT)657 }658659 /// Get effective value for [`sponsor_approve_timeout`](self.sponsor_approve_timeout).660 pub fn sponsor_approve_timeout(&self) -> u32 {661 self.sponsor_approve_timeout662 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)663 .min(MAX_SPONSOR_TIMEOUT)664 }665666 /// Get effective value for [`owner_can_transfer`](self.owner_can_transfer).667 pub fn owner_can_transfer(&self) -> bool {668 self.owner_can_transfer.unwrap_or(false)669 }670671 /// Get effective value for [`owner_can_transfer_instaled`](self.owner_can_transfer_instaled).672 pub fn owner_can_transfer_instaled(&self) -> bool {673 self.owner_can_transfer.is_some()674 }675676 /// Get effective value for [`owner_can_destroy`](self.owner_can_destroy).677 pub fn owner_can_destroy(&self) -> bool {678 self.owner_can_destroy.unwrap_or(true)679 }680681 /// Get effective value for [`transfers_enabled`](self.transfers_enabled).682 pub fn transfers_enabled(&self) -> bool {683 self.transfers_enabled.unwrap_or(true)684 }685686 /// Get effective value for [`sponsored_data_rate_limit`](self.sponsored_data_rate_limit).687 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {688 match self689 .sponsored_data_rate_limit690 .unwrap_or(SponsoringRateLimit::SponsoringDisabled)691 {692 SponsoringRateLimit::SponsoringDisabled => None,693 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),694 }695 }696}697698/// Permissions on certain operations within a collection.699///700/// Some fields are wrapped in [`Option`], where `None` means chain default.701///702/// Update with `pallet_common::Pallet::clamp_permissions`.703#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]704#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]705// When adding/removing fields from this struct - don't forget to also update `pallet_common::Pallet::clamp_permissions`.706// TODO: move `pallet_common::Pallet::clamp_permissions` into `impl CollectionPermissions`.707pub struct CollectionPermissions {708 /// Access mode.709 ///710 /// * Default - [`AccessMode::Normal`].711 pub access: Option<AccessMode>,712713 /// Minting allowance.714 ///715 /// * Default - **false**.716 pub mint_mode: Option<bool>,717718 /// Permissions for nesting.719 ///720 /// * Default721 /// - `token_owner` - **false**722 /// - `collection_admin` - **false**723 /// - `restricted` - **None**724 pub nesting: Option<NestingPermissions>,725}726727impl CollectionPermissions {728 /// Get effective value for [`access`](self.access).729 pub fn access(&self) -> AccessMode {730 self.access.unwrap_or(AccessMode::Normal)731 }732733 /// Get effective value for [`mint_mode`](self.mint_mode).734 pub fn mint_mode(&self) -> bool {735 self.mint_mode.unwrap_or(false)736 }737738 /// Get effective value for [`nesting`](self.nesting).739 pub fn nesting(&self) -> &NestingPermissions {740 static DEFAULT: NestingPermissions = NestingPermissions {741 token_owner: false,742 collection_admin: false,743 restricted: None,744 #[cfg(feature = "runtime-benchmarks")]745 permissive: false,746 };747 self.nesting.as_ref().unwrap_or(&DEFAULT)748 }749}750751/// Inner set for collections allowed to nest.752type OwnerRestrictedSetInner = BoundedBTreeSet<CollectionId, ConstU32<16>>;753754/// Wraper for collections set allowing nest.755#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]756#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]757#[derivative(Debug)]758pub struct OwnerRestrictedSet(759 #[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]760 #[derivative(Debug(format_with = "bounded::set_debug"))]761 pub OwnerRestrictedSetInner,762);763764impl OwnerRestrictedSet {765 /// Create new set.766 pub fn new() -> Self {767 Self(Default::default())768 }769}770impl core::ops::Deref for OwnerRestrictedSet {771 type Target = OwnerRestrictedSetInner;772 fn deref(&self) -> &Self::Target {773 &self.0774 }775}776impl core::ops::DerefMut for OwnerRestrictedSet {777 fn deref_mut(&mut self) -> &mut Self::Target {778 &mut self.0779 }780}781782/// Part of collection permissions, if set, defines who is able to nest tokens into other tokens.783#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]784#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]785#[derivative(Debug)]786pub struct NestingPermissions {787 /// Owner of token can nest tokens under it.788 pub token_owner: bool,789 /// Admin of token collection can nest tokens under token.790 pub collection_admin: bool,791 /// If set - only tokens from specified collections can be nested.792 pub restricted: Option<OwnerRestrictedSet>,793794 #[cfg(feature = "runtime-benchmarks")]795 /// Anyone can nest tokens, mutually exclusive with `token_owner`, `admin`.796 pub permissive: bool,797}798799/// Enum denominating how often can sponsoring occur if it is enabled.800///801/// Used for [`collection limits`](CollectionLimits).802#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]803#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]804pub enum SponsoringRateLimit {805 /// Sponsoring is disabled, and the collection sponsor will not pay for transactions806 SponsoringDisabled,807 /// Once per how many blocks can sponsorship of a transaction type occur808 Blocks(u32),809}810811/// Data used to describe an NFT at creation.812#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]813#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]814#[derivative(Debug)]815pub struct CreateNftData {816 /// Key-value pairs used to describe the token as metadata817 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]818 #[derivative(Debug(format_with = "bounded::vec_debug"))]819 /// Properties that wil be assignet to created item.820 pub properties: CollectionPropertiesVec,821}822823/// Data used to describe a Fungible token at creation.824#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]825#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]826pub struct CreateFungibleData {827 /// Number of fungible coins minted828 pub value: u128,829}830831/// Data used to describe a Refungible token at creation.832#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]833#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]834#[derivative(Debug)]835pub struct CreateReFungibleData {836 /// Number of pieces the RFT is split into837 pub pieces: u128,838839 /// Key-value pairs used to describe the token as metadata840 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]841 #[derivative(Debug(format_with = "bounded::vec_debug"))]842 pub properties: CollectionPropertiesVec,843}844845// TODO: remove this.846#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]847#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]848pub enum MetaUpdatePermission {849 ItemOwner,850 Admin,851 None,852}853854/// Enum holding data used for creation of all three item types.855/// Unified data for create item.856#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]857#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]858pub enum CreateItemData {859 /// Data for create NFT.860 NFT(CreateNftData),861 /// Data for create Fungible item.862 Fungible(CreateFungibleData),863 /// Data for create ReFungible item.864 ReFungible(CreateReFungibleData),865}866867/// Extended data for create NFT.868#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]869#[derivative(Debug)]870pub struct CreateNftExData<CrossAccountId> {871 /// Properties that wil be assignet to created item.872 #[derivative(Debug(format_with = "bounded::vec_debug"))]873 pub properties: CollectionPropertiesVec,874875 /// Owner of creating item.876 pub owner: CrossAccountId,877}878879/// Extended data for create ReFungible item.880#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]881#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]882pub struct CreateRefungibleExMultipleOwners<CrossAccountId> {883 #[derivative(Debug(format_with = "bounded::map_debug"))]884 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,885 #[derivative(Debug(format_with = "bounded::vec_debug"))]886 pub properties: CollectionPropertiesVec,887}888889/// Extended data for create ReFungible item.890#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]891#[derivative(Debug(bound = "CrossAccountId: fmt::Debug"))]892pub struct CreateRefungibleExSingleOwner<CrossAccountId> {893 pub user: CrossAccountId,894 pub pieces: u128,895 #[derivative(Debug(format_with = "bounded::vec_debug"))]896 pub properties: CollectionPropertiesVec,897}898899/// Unified extended data for creating item.900#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]901#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]902pub enum CreateItemExData<CrossAccountId> {903 /// Extended data for create NFT.904 NFT(905 #[derivative(Debug(format_with = "bounded::vec_debug"))]906 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,907 ),908909 /// Extended data for create Fungible item.910 Fungible(911 #[derivative(Debug(format_with = "bounded::map_debug"))]912 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,913 ),914915 /// Extended data for create ReFungible item in case of916 /// many tokens, each may have only one owner917 RefungibleMultipleItems(918 #[derivative(Debug(format_with = "bounded::vec_debug"))]919 BoundedVec<CreateRefungibleExSingleOwner<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,920 ),921922 /// Extended data for create ReFungible item in case of923 /// single token, which may have many owners924 RefungibleMultipleOwners(CreateRefungibleExMultipleOwners<CrossAccountId>),925}926927impl From<CreateNftData> for CreateItemData {928 fn from(item: CreateNftData) -> Self {929 CreateItemData::NFT(item)930 }931}932933impl From<CreateReFungibleData> for CreateItemData {934 fn from(item: CreateReFungibleData) -> Self {935 CreateItemData::ReFungible(item)936 }937}938939impl From<CreateFungibleData> for CreateItemData {940 fn from(item: CreateFungibleData) -> Self {941 CreateItemData::Fungible(item)942 }943}944945/// Token's address, dictated by its collection and token IDs.946#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]947#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]948// todo possibly rename to be used generally as an address pair949pub struct TokenChild {950 /// Token id.951 pub token: TokenId,952953 /// Collection id.954 pub collection: CollectionId,955}956957/// Collection statistics.958#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]959#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]960pub struct CollectionStats {961 /// Number of created items.962 pub created: u32,963964 /// Number of burned items.965 pub destroyed: u32,966967 /// Number of current items.968 pub alive: u32,969}970971/// This type works like [`PhantomData`] but supports generating _scale-info_ descriptions to generate node metadata.972#[derive(Encode, Decode, Clone, Debug)]973#[cfg_attr(feature = "std", derive(PartialEq))]974pub struct PhantomType<T>(core::marker::PhantomData<T>);975976impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {977 type Identity = PhantomType<T>;978979 fn type_info() -> scale_info::Type {980 use scale_info::{981 Type, Path,982 build::{FieldsBuilder, UnnamedFields},983 form::MetaForm,984 type_params,985 };986 Type::builder()987 .path(Path::new("up_data_structs", "PhantomType"))988 .type_params(type_params!(T))989 .composite(990 <FieldsBuilder<MetaForm, UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()),991 )992 }993}994impl<T> MaxEncodedLen for PhantomType<T> {995 fn max_encoded_len() -> usize {996 0997 }998}9991000/// Bounded vector of bytes.1001pub type BoundedBytes<S> = BoundedVec<u8, S>;10021003/// Extra properties for external collections.1004pub type AuxPropertyValue = BoundedBytes<ConstU32<MAX_AUX_PROPERTY_VALUE_LENGTH>>;10051006/// Property key.1007pub type PropertyKey = BoundedBytes<ConstU32<MAX_PROPERTY_KEY_LENGTH>>;10081009/// Property value.1010pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;10111012/// Property permission.1013#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]1014#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1015pub struct PropertyPermission {1016 /// Permission to change the property and property permission.1017 ///1018 /// If it **false** then you can not change corresponding property even if [`collection_admin`] and [`token_owner`] are **true**.1019 pub mutable: bool,10201021 /// Change permission for the collection administrator.1022 pub collection_admin: bool,10231024 /// Permission to change the property for the owner of the token.1025 pub token_owner: bool,1026}10271028impl PropertyPermission {1029 /// Creates mutable property permission but changes restricted for collection admin and token owner.1030 pub fn none() -> Self {1031 Self {1032 mutable: true,1033 collection_admin: false,1034 token_owner: false,1035 }1036 }1037}10381039/// Property is simpl key-value record.1040#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]1041#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1042pub struct Property {1043 /// Property key.1044 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1045 pub key: PropertyKey,10461047 /// Property value.1048 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1049 pub value: PropertyValue,1050}10511052impl Into<(PropertyKey, PropertyValue)> for Property {1053 fn into(self) -> (PropertyKey, PropertyValue) {1054 (self.key, self.value)1055 }1056}10571058/// Record for proprty key permission.1059#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]1060#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1061pub struct PropertyKeyPermission {1062 /// Key.1063 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1064 pub key: PropertyKey,10651066 /// Permission.1067 pub permission: PropertyPermission,1068}10691070impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {1071 fn into(self) -> (PropertyKey, PropertyPermission) {1072 (self.key, self.permission)1073 }1074}10751076/// Errors for properties actions.1077#[derive(Debug)]1078pub enum PropertiesError {1079 /// The space allocated for properties has run out.1080 ///1081 /// * Limit for colection - [`MAX_COLLECTION_PROPERTIES_SIZE`].1082 /// * Limit for token - [`MAX_TOKEN_PROPERTIES_SIZE`].1083 NoSpaceForProperty,10841085 /// The property limit has been reached.1086 ///1087 /// * Limit - [`MAX_PROPERTIES_PER_ITEM`].1088 PropertyLimitReached,10891090 /// Property key contains not allowed character.1091 InvalidCharacterInPropertyKey,10921093 /// Property key length is too long.1094 ///1095 /// * Limit - [`MAX_PROPERTY_KEY_LENGTH`].1096 PropertyKeyIsTooLong,10971098 /// Property key is empty.1099 EmptyPropertyKey,1100}11011102/// Marker for scope of property.1103///1104/// Scoped property can't be changed by user. Used for external collections.1105#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Clone, Copy)]1106pub enum PropertyScope {1107 None,1108 Rmrk,1109}11101111impl PropertyScope {1112 /// Apply scope to property key.1113 pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {1114 let scope_str: &[u8] = match self {1115 Self::None => return Ok(key),1116 Self::Rmrk => b"rmrk",1117 };11181119 [scope_str, b":", key.as_slice()]1120 .concat()1121 .try_into()1122 .map_err(|_| PropertiesError::PropertyKeyIsTooLong)1123 }1124}11251126/// Trait for operate with properties.1127pub trait TrySetProperty: Sized {1128 type Value;11291130 /// Try to set property with scope.1131 fn try_scoped_set(1132 &mut self,1133 scope: PropertyScope,1134 key: PropertyKey,1135 value: Self::Value,1136 ) -> Result<Option<Self::Value>, PropertiesError>;11371138 /// Try to set property with scope from iterator.1139 fn try_scoped_set_from_iter<I, KV>(1140 &mut self,1141 scope: PropertyScope,1142 iter: I,1143 ) -> Result<(), PropertiesError>1144 where1145 I: Iterator<Item = KV>,1146 KV: Into<(PropertyKey, Self::Value)>,1147 {1148 for kv in iter {1149 let (key, value) = kv.into();1150 self.try_scoped_set(scope, key, value)?;1151 }11521153 Ok(())1154 }11551156 /// Try to set property.1157 fn try_set(1158 &mut self,1159 key: PropertyKey,1160 value: Self::Value,1161 ) -> Result<Option<Self::Value>, PropertiesError> {1162 self.try_scoped_set(PropertyScope::None, key, value)1163 }11641165 /// Try to set property from iterator.1166 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>1167 where1168 I: Iterator<Item = KV>,1169 KV: Into<(PropertyKey, Self::Value)>,1170 {1171 self.try_scoped_set_from_iter(PropertyScope::None, iter)1172 }1173}11741175/// Wrapped map for storing properties.1176#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]1177#[derivative(Default(bound = ""))]1178pub struct PropertiesMap<Value>(1179 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,1180);11811182impl<Value> PropertiesMap<Value> {1183 /// Create new property map.1184 pub fn new() -> Self {1185 Self(BoundedBTreeMap::new())1186 }11871188 /// Remove property from map.1189 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {1190 Self::check_property_key(key)?;11911192 Ok(self.0.remove(key))1193 }11941195 /// Get property with appropriate key from map.1196 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {1197 self.0.get(key)1198 }11991200 /// Check if map contains key.1201 pub fn contains_key(&self, key: &PropertyKey) -> bool {1202 self.0.contains_key(key)1203 }12041205 /// Check if map contains key with key validation.1206 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {1207 if key.is_empty() {1208 return Err(PropertiesError::EmptyPropertyKey);1209 }12101211 for byte in key.as_slice().iter() {1212 let byte = *byte;12131214 if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' && byte != b'.' {1215 return Err(PropertiesError::InvalidCharacterInPropertyKey);1216 }1217 }12181219 Ok(())1220 }12211222 pub fn values(&self) -> impl Iterator<Item = &Value> {1223 self.0.values()1224 }1225}12261227impl<Value> IntoIterator for PropertiesMap<Value> {1228 type Item = (PropertyKey, Value);1229 type IntoIter = <1230 BoundedBTreeMap<1231 PropertyKey,1232 Value,1233 ConstU32<MAX_PROPERTIES_PER_ITEM>1234 > as IntoIterator1235 >::IntoIter;12361237 fn into_iter(self) -> Self::IntoIter {1238 self.0.into_iter()1239 }1240}12411242impl<Value> TrySetProperty for PropertiesMap<Value> {1243 type Value = Value;12441245 fn try_scoped_set(1246 &mut self,1247 scope: PropertyScope,1248 key: PropertyKey,1249 value: Self::Value,1250 ) -> Result<Option<Self::Value>, PropertiesError> {1251 Self::check_property_key(&key)?;12521253 let key = scope.apply(key)?;1254 self.01255 .try_insert(key, value)1256 .map_err(|_| PropertiesError::PropertyLimitReached)1257 }1258}12591260/// Alias for property permissions map.1261pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;12621263/// Wrapper for properties map with consumed space control.1264#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]1265pub struct Properties {1266 map: PropertiesMap<PropertyValue>,1267 consumed_space: u32,1268 space_limit: u32,1269}12701271impl Properties {1272 /// Create new properies container.1273 pub fn new(space_limit: u32) -> Self {1274 Self {1275 map: PropertiesMap::new(),1276 consumed_space: 0,1277 space_limit,1278 }1279 }12801281 /// Remove propery with appropiate key.1282 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {1283 let value = self.map.remove(key)?;12841285 if let Some(ref value) = value {1286 let value_len = value.len() as u32;1287 self.consumed_space -= value_len;1288 }12891290 Ok(value)1291 }12921293 /// Get property with appropriate key.1294 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {1295 self.map.get(key)1296 }12971298 /// Recomputes the consumed space for the current properties state.1299 /// Needed to repair a token due to a bug fixed in the [PR #733](https://github.com/UniqueNetwork/unique-chain/pull/773).1300 pub fn recompute_consumed_space(&mut self) {1301 self.consumed_space = self.map.values().map(|value| value.len() as u32).sum();1302 }1303}13041305impl IntoIterator for Properties {1306 type Item = (PropertyKey, PropertyValue);1307 type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;13081309 fn into_iter(self) -> Self::IntoIter {1310 self.map.into_iter()1311 }1312}13131314impl TrySetProperty for Properties {1315 type Value = PropertyValue;13161317 fn try_scoped_set(1318 &mut self,1319 scope: PropertyScope,1320 key: PropertyKey,1321 value: Self::Value,1322 ) -> Result<Option<Self::Value>, PropertiesError> {1323 let value_len = value.len();13241325 if self.consumed_space as usize + value_len > self.space_limit as usize1326 && !cfg!(feature = "runtime-benchmarks")1327 {1328 return Err(PropertiesError::NoSpaceForProperty);1329 }13301331 let value_len = value_len as u32;1332 let old_value = self.map.try_scoped_set(scope, key, value)?;13331334 let old_value_len = old_value.as_ref().map(|v| v.len() as u32).unwrap_or(0);13351336 if value_len > old_value_len {1337 self.consumed_space += value_len - old_value_len;1338 } else {1339 self.consumed_space -= old_value_len - value_len;1340 }13411342 Ok(old_value)1343 }1344}13451346/// Utility struct for using in `StorageMap`.1347pub struct CollectionProperties;13481349impl Get<Properties> for CollectionProperties {1350 fn get() -> Properties {1351 Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)1352 }1353}13541355/// Utility struct for using in `StorageMap`.1356pub struct TokenProperties;13571358impl Get<Properties> for TokenProperties {1359 fn get() -> Properties {1360 Properties::new(MAX_TOKEN_PROPERTIES_SIZE)1361 }1362}13631364// RMRK1365// todo document?1366parameter_types! {1367 #[derive(PartialEq, TypeInfo)]1368 pub const RmrkStringLimit: u32 = 128;1369 #[derive(PartialEq)]1370 pub const RmrkCollectionSymbolLimit: u32 = MAX_TOKEN_PREFIX_LENGTH;1371 #[derive(PartialEq)]1372 pub const RmrkResourceSymbolLimit: u32 = 10;1373 #[derive(PartialEq)]1374 pub const RmrkBaseSymbolLimit: u32 = MAX_TOKEN_PREFIX_LENGTH;1375 #[derive(PartialEq)]1376 pub const RmrkKeyLimit: u32 = 32;1377 #[derive(PartialEq)]1378 pub const RmrkValueLimit: u32 = 256;1379 #[derive(PartialEq)]1380 pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;1381 #[derive(PartialEq)]1382 pub const MaxPropertiesPerTheme: u32 = 5;1383 #[derive(PartialEq)]1384 pub const RmrkPartsLimit: u32 = 25;1385 #[derive(PartialEq)]1386 pub const RmrkMaxPriorities: u32 = 25;1387 #[derive(PartialEq)]1388 pub const MaxResourcesOnMint: u32 = 100;1389}13901391impl From<RmrkCollectionId> for CollectionId {1392 fn from(id: RmrkCollectionId) -> Self {1393 Self(id)1394 }1395}13961397impl From<RmrkNftId> for TokenId {1398 fn from(id: RmrkNftId) -> Self {1399 Self(id)1400 }1401}14021403pub type RmrkCollectionInfo<AccountId> =1404 CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;1405pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;1406pub type RmrkResourceInfo = ResourceInfo<RmrkString, RmrkBoundedParts>;1407pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;1408pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;1409pub type BoundedEquippableCollectionIds =1410 BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>;1411pub type RmrkPartType = PartType<RmrkString, BoundedEquippableCollectionIds>;1412pub type RmrkEquippableList = EquippableList<BoundedEquippableCollectionIds>;1413pub type RmrkThemeProperty = ThemeProperty<RmrkString>;1414pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;1415pub type RmrkBoundedTheme = Theme<RmrkString, BoundedVec<RmrkThemeProperty, MaxPropertiesPerTheme>>;1416pub type RmrkResourceTypes = ResourceTypes<RmrkString, RmrkBoundedParts>;14171418pub type RmrkBasicResource = BasicResource<RmrkString>;1419pub type RmrkComposableResource = ComposableResource<RmrkString, RmrkBoundedParts>;1420pub type RmrkSlotResource = SlotResource<RmrkString>;14211422pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;1423pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;1424pub type RmrkBaseSymbol = BoundedVec<u8, RmrkBaseSymbolLimit>;1425pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;1426pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;1427pub type RmrkBoundedResource = BoundedVec<u8, RmrkResourceSymbolLimit>;1428pub type RmrkBoundedParts = BoundedVec<RmrkPartId, RmrkPartsLimit>; // todo make sure it is needed14291430pub type RmrkRpcString = Vec<u8>;1431pub type RmrkThemeName = RmrkRpcString;1432pub type RmrkPropertyKey = RmrkRpcString;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//! # Primitives crate.18//!19//! This crate contains types, traits and constants.2021#![cfg_attr(not(feature = "std"), no_std)]2223use core::{24 convert::{TryFrom, TryInto},25 fmt,26};27use frame_support::{28 storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},29 traits::Get,30 parameter_types,31};3233#[cfg(feature = "serde")]34use serde::{Serialize, Deserialize};3536use sp_core::U256;37use sp_runtime::{ArithmeticError, sp_std::prelude::Vec, Permill};38use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};39use bondrewd::Bitfields;40use frame_support::{BoundedVec, traits::ConstU32};41use derivative::Derivative;42use scale_info::TypeInfo;4344// RMRK45use rmrk_traits::{46 CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme, ThemeProperty,47 ResourceTypes, BasicResource, ComposableResource, SlotResource, EquippableList,48};49pub use rmrk_traits::{50 primitives::{51 CollectionId as RmrkCollectionId, NftId as RmrkNftId, BaseId as RmrkBaseId,52 SlotId as RmrkSlotId, PartId as RmrkPartId, ResourceId as RmrkResourceId,53 },54 NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,55 FixedPart as RmrkFixedPart, SlotPart as RmrkSlotPart,56};5758mod bondrewd_codec;59mod bounded;60pub mod budget;61pub mod mapping;62mod migration;6364/// Maximum of decimal points.65pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;6667/// Maximum pieces for refungible token.68pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;69pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;7071/// Maximum tokens for user.72pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {73 100_00074} else {75 1076};7778/// Maximum for collections can be created.79pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {80 100_00081} else {82 1083};8485/// Maximum for various custom data of token.86pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {87 204888} else {89 1090};9192/// Maximum admins per collection.93pub const COLLECTION_ADMINS_LIMIT: u32 = 5;9495/// Maximum tokens per collection.96pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;9798/// Maximum tokens per account.99pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {100 1_000_000101} else {102 10103};104105/// Default timeout for transfer sponsoring NFT item.106pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;107/// Default timeout for transfer sponsoring fungible item.108pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;109/// Default timeout for transfer sponsoring refungible item.110pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;111112/// Default timeout for sponsored approving.113pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;114115// Schema limits116pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;117pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;118pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;119120// TODO: not used. Delete?121pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;122123/// Maximal length of a collection name.124pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;125126/// Maximal length of a collection description.127pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;128129/// Maximal length of a token prefix.130pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;131132/// Maximal length of a property key.133pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;134135/// Maximal length of a property value.136pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;137138/// A maximum number of token properties.139pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;140141/// Maximal lenght of extended property value.142pub const MAX_AUX_PROPERTY_VALUE_LENGTH: u32 = 2048;143144/// Maximum size for all collection properties.145pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;146147/// Maximum size of all token properties.148pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;149150/// How much items can be created per single151/// create_many call.152pub const MAX_ITEMS_PER_BATCH: u32 = 200;153154/// Used for limit bounded types of token custom data.155pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;156157/// Collection id.158#[derive(159 Encode,160 Decode,161 PartialEq,162 Eq,163 PartialOrd,164 Ord,165 Clone,166 Copy,167 Debug,168 Default,169 TypeInfo,170 MaxEncodedLen,171)]172#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]173pub struct CollectionId(pub u32);174impl EncodeLike<u32> for CollectionId {}175impl EncodeLike<CollectionId> for u32 {}176177/// Token id.178#[derive(179 Encode,180 Decode,181 PartialEq,182 Eq,183 PartialOrd,184 Ord,185 Clone,186 Copy,187 Debug,188 Default,189 TypeInfo,190 MaxEncodedLen,191)]192#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]193pub struct TokenId(pub u32);194impl EncodeLike<u32> for TokenId {}195impl EncodeLike<TokenId> for u32 {}196197impl TokenId {198 /// Try to get next token id.199 ///200 /// If next id cause overflow, then [`ArithmeticError::Overflow`] returned.201 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {202 self.0203 .checked_add(1)204 .ok_or(ArithmeticError::Overflow)205 .map(Self)206 }207}208209impl From<TokenId> for U256 {210 fn from(t: TokenId) -> Self {211 t.0.into()212 }213}214215impl TryFrom<U256> for TokenId {216 type Error = &'static str;217218 fn try_from(value: U256) -> Result<Self, Self::Error> {219 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))220 }221}222223/// Token data.224#[struct_versioning::versioned(version = 2, upper)]225#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]226#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]227pub struct TokenData<CrossAccountId> {228 /// Properties of token.229 pub properties: Vec<Property>,230231 /// Token owner.232 pub owner: Option<CrossAccountId>,233234 /// Token pieces.235 #[version(2.., upper(0))]236 pub pieces: u128,237}238239// TODO: unused type240pub struct OverflowError;241impl From<OverflowError> for &'static str {242 fn from(_: OverflowError) -> Self {243 "overflow occured"244 }245}246247/// Alias for decimal points type.248pub type DecimalPoints = u8;249250/// Collection mode.251///252/// Collection can represent various types of tokens.253/// Each collection can contain only one type of tokens at a time.254/// This type helps to understand which tokens the collection contains.255#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]256#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]257pub enum CollectionMode {258 /// Non fungible tokens.259 NFT,260 /// Fungible tokens.261 Fungible(DecimalPoints),262 /// Refungible tokens.263 ReFungible,264}265266impl CollectionMode {267 /// Get collection mod as number.268 pub fn id(&self) -> u8 {269 match self {270 CollectionMode::NFT => 1,271 CollectionMode::Fungible(_) => 2,272 CollectionMode::ReFungible => 3,273 }274 }275}276277// TODO: unused trait278pub trait SponsoringResolve<AccountId, Call> {279 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;280}281282/// Access mode for some token operations.283#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]284#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]285pub enum AccessMode {286 /// Access grant for owner and admins. Used as default.287 Normal,288 /// Like a [`Normal`](AccessMode::Normal) but also users in allow list.289 AllowList,290}291impl Default for AccessMode {292 fn default() -> Self {293 Self::Normal294 }295}296297// TODO: remove in future.298#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]299#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]300pub enum SchemaVersion {301 ImageURL,302 Unique,303}304impl Default for SchemaVersion {305 fn default() -> Self {306 Self::ImageURL307 }308}309310// TODO: unused type311#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]312#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]313pub struct Ownership<AccountId> {314 pub owner: AccountId,315 pub fraction: u128,316}317318/// The state of collection sponsorship.319#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]320#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]321pub enum SponsorshipState<AccountId> {322 /// The fees are applied to the transaction sender.323 Disabled,324 /// The sponsor is under consideration. Until the sponsor gives his consent,325 /// the fee will still be charged to sender.326 Unconfirmed(AccountId),327 /// Transactions are sponsored by specified account.328 Confirmed(AccountId),329}330331impl<AccountId> SponsorshipState<AccountId> {332 /// Get a sponsor of the collection who has confirmed his status.333 pub fn sponsor(&self) -> Option<&AccountId> {334 match self {335 Self::Confirmed(sponsor) => Some(sponsor),336 _ => None,337 }338 }339340 /// Get a sponsor of the collection who has pending or confirmed status.341 pub fn pending_sponsor(&self) -> Option<&AccountId> {342 match self {343 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),344 _ => None,345 }346 }347348 /// Whether the sponsorship is confirmed.349 pub fn confirmed(&self) -> bool {350 matches!(self, Self::Confirmed(_))351 }352}353354impl<T> Default for SponsorshipState<T> {355 fn default() -> Self {356 Self::Disabled357 }358}359360pub type CollectionName = BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>;361pub type CollectionDescription = BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>;362pub type CollectionTokenPrefix = BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>;363364#[derive(Bitfields, Clone, Copy, PartialEq, Eq, Debug, Default)]365#[bondrewd(enforce_bytes = 1)]366pub struct CollectionFlags {367 /// Tokens in foreign collections can be transferred, but not burnt368 #[bondrewd(bits = "0..1")]369 pub foreign: bool,370 /// Supports ERC721Metadata371 #[bondrewd(bits = "1..2")]372 pub erc721metadata: bool,373 /// External collections can't be managed using `unique` api374 #[bondrewd(bits = "7..8")]375 pub external: bool,376377 #[bondrewd(reserve, bits = "2..7")]378 pub reserved: u8,379}380bondrewd_codec!(CollectionFlags);381382/// Base structure for represent collection.383///384/// Used to provide basic functionality for all types of collections.385///386/// #### Note387/// Collection parameters, used in storage (see [`RpcCollection`] for the RPC version).388#[struct_versioning::versioned(version = 2, upper)]389#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]390pub struct Collection<AccountId> {391 /// Collection owner account.392 pub owner: AccountId,393394 /// Collection mode.395 pub mode: CollectionMode,396397 /// Access mode.398 #[version(..2)]399 pub access: AccessMode,400401 /// Collection name.402 pub name: CollectionName,403404 /// Collection description.405 pub description: CollectionDescription,406407 /// Token prefix.408 pub token_prefix: CollectionTokenPrefix,409410 #[version(..2)]411 pub mint_mode: bool,412413 #[version(..2)]414 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,415416 #[version(..2)]417 pub schema_version: SchemaVersion,418419 /// The state of sponsorship of the collection.420 pub sponsorship: SponsorshipState<AccountId>,421422 /// Collection limits.423 pub limits: CollectionLimits,424425 /// Collection permissions.426 #[version(2.., upper(Default::default()))]427 pub permissions: CollectionPermissions,428429 #[version(2.., upper(Default::default()))]430 pub flags: CollectionFlags,431432 #[version(..2)]433 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,434435 #[version(..2)]436 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,437438 #[version(..2)]439 pub meta_update_permission: MetaUpdatePermission,440}441442#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]443#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]444pub struct RpcCollectionFlags {445 /// Is collection is foreign.446 pub foreign: bool,447 /// Collection supports ERC721Metadata.448 pub erc721metadata: bool,449}450451/// Collection parameters, used in RPC calls (see [`Collection`] for the storage version).452#[struct_versioning::versioned(version = 2, upper)]453#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]454#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]455pub struct RpcCollection<AccountId> {456 /// Collection owner account.457 pub owner: AccountId,458459 /// Collection mode.460 pub mode: CollectionMode,461462 /// Collection name.463 pub name: Vec<u16>,464465 /// Collection description.466 pub description: Vec<u16>,467468 /// Token prefix.469 pub token_prefix: Vec<u8>,470471 /// The state of sponsorship of the collection.472 pub sponsorship: SponsorshipState<AccountId>,473474 /// Collection limits.475 pub limits: CollectionLimits,476477 /// Collection permissions.478 pub permissions: CollectionPermissions,479480 /// Token property permissions.481 pub token_property_permissions: Vec<PropertyKeyPermission>,482483 /// Collection properties.484 pub properties: Vec<Property>,485486 /// Is collection read only.487 pub read_only: bool,488489 /// Extra collection flags490 #[version(2.., upper(RpcCollectionFlags {foreign: false, erc721metadata: false}))]491 pub flags: RpcCollectionFlags,492}493494/// Data used for create collection.495///496/// All fields are wrapped in [`Option`], where `None` means chain default.497#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]498#[derivative(Debug, Default(bound = ""))]499pub struct CreateCollectionData<AccountId> {500 /// Collection mode.501 #[derivative(Default(value = "CollectionMode::NFT"))]502 pub mode: CollectionMode,503504 /// Access mode.505 pub access: Option<AccessMode>,506507 /// Collection name.508 pub name: CollectionName,509510 /// Collection description.511 pub description: CollectionDescription,512513 /// Token prefix.514 pub token_prefix: CollectionTokenPrefix,515516 /// Pending collection sponsor.517 pub pending_sponsor: Option<AccountId>,518519 /// Collection limits.520 pub limits: Option<CollectionLimits>,521522 /// Collection permissions.523 pub permissions: Option<CollectionPermissions>,524525 /// Token property permissions.526 pub token_property_permissions: CollectionPropertiesPermissionsVec,527528 /// Collection properties.529 pub properties: CollectionPropertiesVec,530}531532/// Bounded vector of properties permissions. Max length is [`MAX_PROPERTIES_PER_ITEM`].533// TODO: maybe rename to PropertiesPermissionsVec534pub type CollectionPropertiesPermissionsVec =535 BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;536537/// Bounded vector of properties. Max length is [`MAX_PROPERTIES_PER_ITEM`].538pub type CollectionPropertiesVec = BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;539540/// Limits and restrictions of a collection.541///542/// All fields are wrapped in [`Option`], where `None` means chain default.543///544/// Update with `pallet_common::Pallet::clamp_limits`.545// IMPORTANT: When adding/removing fields from this struct - don't forget to also546#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]547#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]548// When adding/removing fields from this struct - don't forget to also update with `pallet_common::Pallet::clamp_limits`.549// TODO: move `pallet_common::Pallet::clamp_limits` into `impl CollectionLimits`.550// TODO: may be remove [`Option`] and **pub** from fields and create struct with default values.551pub struct CollectionLimits {552 /// How many tokens can a user have on one account.553 /// * Default - [`ACCOUNT_TOKEN_OWNERSHIP_LIMIT`].554 /// * Limit - [`MAX_TOKEN_OWNERSHIP`].555 pub account_token_ownership_limit: Option<u32>,556557 /// How many bytes of data are available for sponsorship.558 /// * Default - [`CUSTOM_DATA_LIMIT`].559 /// * Limit - [`CUSTOM_DATA_LIMIT`].560 pub sponsored_data_size: Option<u32>,561562 // FIXME should we delete this or repurpose it?563 /// Times in how many blocks we sponsor data.564 ///565 /// If is `Some(v)` then **setVariableMetadata** is sponsored if there is `v` block between transactions.566 ///567 /// * Default - [`SponsoringDisabled`](SponsoringRateLimit::SponsoringDisabled).568 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].569 ///570 /// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]571 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,572 /// Maximum amount of tokens inside the collection. Chain default: [`COLLECTION_TOKEN_LIMIT`]573574 /// How many tokens can be mined into this collection.575 ///576 /// * Default - [`COLLECTION_TOKEN_LIMIT`].577 /// * Limit - [`COLLECTION_TOKEN_LIMIT`].578 pub token_limit: Option<u32>,579580 /// Timeouts for transfer sponsoring.581 ///582 /// * Default583 /// - **Fungible** - [`FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`]584 /// - **NFT** - [`NFT_SPONSOR_TRANSFER_TIMEOUT`]585 /// - **Refungible** - [`REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`]586 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].587 pub sponsor_transfer_timeout: Option<u32>,588589 /// Timeout for sponsoring an approval in passed blocks.590 ///591 /// * Default - [`SPONSOR_APPROVE_TIMEOUT`].592 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].593 pub sponsor_approve_timeout: Option<u32>,594595 /// Whether the collection owner of the collection can send tokens (which belong to other users).596 ///597 /// * Default - **false**.598 pub owner_can_transfer: Option<bool>,599600 /// Can the collection owner burn other people's tokens.601 ///602 /// * Default - **true**.603 pub owner_can_destroy: Option<bool>,604605 /// Is it possible to send tokens from this collection between users.606 ///607 /// * Default - **true**.608 pub transfers_enabled: Option<bool>,609}610611impl CollectionLimits {612 pub fn with_default_limits(collection_type: CollectionMode) -> Self {613 CollectionLimits {614 account_token_ownership_limit: Some(ACCOUNT_TOKEN_OWNERSHIP_LIMIT),615 sponsored_data_size: Some(CUSTOM_DATA_LIMIT),616 sponsored_data_rate_limit: Some(SponsoringRateLimit::SponsoringDisabled),617 token_limit: Some(COLLECTION_TOKEN_LIMIT),618 sponsor_transfer_timeout: match collection_type {619 CollectionMode::NFT => Some(NFT_SPONSOR_TRANSFER_TIMEOUT),620 CollectionMode::ReFungible => Some(REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT),621 CollectionMode::Fungible(_) => Some(FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT),622 },623 sponsor_approve_timeout: Some(SPONSOR_APPROVE_TIMEOUT),624 owner_can_transfer: Some(false),625 owner_can_destroy: Some(true),626 transfers_enabled: Some(true),627 }628 }629630 /// Get effective value for [`account_token_ownership_limit`](self.account_token_ownership_limit).631 pub fn account_token_ownership_limit(&self) -> u32 {632 self.account_token_ownership_limit633 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)634 .min(MAX_TOKEN_OWNERSHIP)635 }636637 /// Get effective value for [`sponsored_data_size`](self.sponsored_data_size).638 pub fn sponsored_data_size(&self) -> u32 {639 self.sponsored_data_size640 .unwrap_or(CUSTOM_DATA_LIMIT)641 .min(CUSTOM_DATA_LIMIT)642 }643644 /// Get effective value for [`token_limit`](self.token_limit).645 pub fn token_limit(&self) -> u32 {646 self.token_limit647 .unwrap_or(COLLECTION_TOKEN_LIMIT)648 .min(COLLECTION_TOKEN_LIMIT)649 }650651 // TODO: may be replace u32 to mode?652 /// Get effective value for [`sponsor_transfer_timeout`](self.sponsor_transfer_timeout).653 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {654 self.sponsor_transfer_timeout655 .unwrap_or(default)656 .min(MAX_SPONSOR_TIMEOUT)657 }658659 /// Get effective value for [`sponsor_approve_timeout`](self.sponsor_approve_timeout).660 pub fn sponsor_approve_timeout(&self) -> u32 {661 self.sponsor_approve_timeout662 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)663 .min(MAX_SPONSOR_TIMEOUT)664 }665666 /// Get effective value for [`owner_can_transfer`](self.owner_can_transfer).667 pub fn owner_can_transfer(&self) -> bool {668 self.owner_can_transfer.unwrap_or(false)669 }670671 /// Get effective value for [`owner_can_transfer_instaled`](self.owner_can_transfer_instaled).672 pub fn owner_can_transfer_instaled(&self) -> bool {673 self.owner_can_transfer.is_some()674 }675676 /// Get effective value for [`owner_can_destroy`](self.owner_can_destroy).677 pub fn owner_can_destroy(&self) -> bool {678 self.owner_can_destroy.unwrap_or(true)679 }680681 /// Get effective value for [`transfers_enabled`](self.transfers_enabled).682 pub fn transfers_enabled(&self) -> bool {683 self.transfers_enabled.unwrap_or(true)684 }685686 /// Get effective value for [`sponsored_data_rate_limit`](self.sponsored_data_rate_limit).687 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {688 match self689 .sponsored_data_rate_limit690 .unwrap_or(SponsoringRateLimit::SponsoringDisabled)691 {692 SponsoringRateLimit::SponsoringDisabled => None,693 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),694 }695 }696}697698/// Permissions on certain operations within a collection.699///700/// Some fields are wrapped in [`Option`], where `None` means chain default.701///702/// Update with `pallet_common::Pallet::clamp_permissions`.703#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]704#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]705// When adding/removing fields from this struct - don't forget to also update `pallet_common::Pallet::clamp_permissions`.706// TODO: move `pallet_common::Pallet::clamp_permissions` into `impl CollectionPermissions`.707pub struct CollectionPermissions {708 /// Access mode.709 ///710 /// * Default - [`AccessMode::Normal`].711 pub access: Option<AccessMode>,712713 /// Minting allowance.714 ///715 /// * Default - **false**.716 pub mint_mode: Option<bool>,717718 /// Permissions for nesting.719 ///720 /// * Default721 /// - `token_owner` - **false**722 /// - `collection_admin` - **false**723 /// - `restricted` - **None**724 pub nesting: Option<NestingPermissions>,725}726727impl CollectionPermissions {728 /// Get effective value for [`access`](self.access).729 pub fn access(&self) -> AccessMode {730 self.access.unwrap_or(AccessMode::Normal)731 }732733 /// Get effective value for [`mint_mode`](self.mint_mode).734 pub fn mint_mode(&self) -> bool {735 self.mint_mode.unwrap_or(false)736 }737738 /// Get effective value for [`nesting`](self.nesting).739 pub fn nesting(&self) -> &NestingPermissions {740 static DEFAULT: NestingPermissions = NestingPermissions {741 token_owner: false,742 collection_admin: false,743 restricted: None,744 #[cfg(feature = "runtime-benchmarks")]745 permissive: false,746 };747 self.nesting.as_ref().unwrap_or(&DEFAULT)748 }749}750751/// Inner set for collections allowed to nest.752type OwnerRestrictedSetInner = BoundedBTreeSet<CollectionId, ConstU32<16>>;753754/// Wraper for collections set allowing nest.755#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]756#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]757#[derivative(Debug)]758pub struct OwnerRestrictedSet(759 #[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]760 #[derivative(Debug(format_with = "bounded::set_debug"))]761 pub OwnerRestrictedSetInner,762);763764impl OwnerRestrictedSet {765 /// Create new set.766 pub fn new() -> Self {767 Self(Default::default())768 }769}770impl core::ops::Deref for OwnerRestrictedSet {771 type Target = OwnerRestrictedSetInner;772 fn deref(&self) -> &Self::Target {773 &self.0774 }775}776impl core::ops::DerefMut for OwnerRestrictedSet {777 fn deref_mut(&mut self) -> &mut Self::Target {778 &mut self.0779 }780}781782/// Part of collection permissions, if set, defines who is able to nest tokens into other tokens.783#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]784#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]785#[derivative(Debug)]786pub struct NestingPermissions {787 /// Owner of token can nest tokens under it.788 pub token_owner: bool,789 /// Admin of token collection can nest tokens under token.790 pub collection_admin: bool,791 /// If set - only tokens from specified collections can be nested.792 pub restricted: Option<OwnerRestrictedSet>,793794 #[cfg(feature = "runtime-benchmarks")]795 /// Anyone can nest tokens, mutually exclusive with `token_owner`, `admin`.796 pub permissive: bool,797}798799/// Enum denominating how often can sponsoring occur if it is enabled.800///801/// Used for [`collection limits`](CollectionLimits).802#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]803#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]804pub enum SponsoringRateLimit {805 /// Sponsoring is disabled, and the collection sponsor will not pay for transactions806 SponsoringDisabled,807 /// Once per how many blocks can sponsorship of a transaction type occur808 Blocks(u32),809}810811/// Data used to describe an NFT at creation.812#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]813#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]814#[derivative(Debug)]815pub struct CreateNftData {816 /// Key-value pairs used to describe the token as metadata817 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]818 #[derivative(Debug(format_with = "bounded::vec_debug"))]819 /// Properties that wil be assignet to created item.820 pub properties: CollectionPropertiesVec,821}822823/// Data used to describe a Fungible token at creation.824#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]825#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]826pub struct CreateFungibleData {827 /// Number of fungible coins minted828 pub value: u128,829}830831/// Data used to describe a Refungible token at creation.832#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]833#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]834#[derivative(Debug)]835pub struct CreateReFungibleData {836 /// Number of pieces the RFT is split into837 pub pieces: u128,838839 /// Key-value pairs used to describe the token as metadata840 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]841 #[derivative(Debug(format_with = "bounded::vec_debug"))]842 pub properties: CollectionPropertiesVec,843}844845// TODO: remove this.846#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]847#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]848pub enum MetaUpdatePermission {849 ItemOwner,850 Admin,851 None,852}853854/// Enum holding data used for creation of all three item types.855/// Unified data for create item.856#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]857#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]858pub enum CreateItemData {859 /// Data for create NFT.860 NFT(CreateNftData),861 /// Data for create Fungible item.862 Fungible(CreateFungibleData),863 /// Data for create ReFungible item.864 ReFungible(CreateReFungibleData),865}866867/// Extended data for create NFT.868#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]869#[derivative(Debug)]870pub struct CreateNftExData<CrossAccountId> {871 /// Properties that wil be assignet to created item.872 #[derivative(Debug(format_with = "bounded::vec_debug"))]873 pub properties: CollectionPropertiesVec,874875 /// Owner of creating item.876 pub owner: CrossAccountId,877}878879/// Extended data for create ReFungible item.880#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]881#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]882pub struct CreateRefungibleExMultipleOwners<CrossAccountId> {883 #[derivative(Debug(format_with = "bounded::map_debug"))]884 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,885 #[derivative(Debug(format_with = "bounded::vec_debug"))]886 pub properties: CollectionPropertiesVec,887}888889/// Extended data for create ReFungible item.890#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]891#[derivative(Debug(bound = "CrossAccountId: fmt::Debug"))]892pub struct CreateRefungibleExSingleOwner<CrossAccountId> {893 pub user: CrossAccountId,894 pub pieces: u128,895 #[derivative(Debug(format_with = "bounded::vec_debug"))]896 pub properties: CollectionPropertiesVec,897}898899/// Unified extended data for creating item.900#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]901#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]902pub enum CreateItemExData<CrossAccountId> {903 /// Extended data for create NFT.904 NFT(905 #[derivative(Debug(format_with = "bounded::vec_debug"))]906 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,907 ),908909 /// Extended data for create Fungible item.910 Fungible(911 #[derivative(Debug(format_with = "bounded::map_debug"))]912 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,913 ),914915 /// Extended data for create ReFungible item in case of916 /// many tokens, each may have only one owner917 RefungibleMultipleItems(918 #[derivative(Debug(format_with = "bounded::vec_debug"))]919 BoundedVec<CreateRefungibleExSingleOwner<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,920 ),921922 /// Extended data for create ReFungible item in case of923 /// single token, which may have many owners924 RefungibleMultipleOwners(CreateRefungibleExMultipleOwners<CrossAccountId>),925}926927impl From<CreateNftData> for CreateItemData {928 fn from(item: CreateNftData) -> Self {929 CreateItemData::NFT(item)930 }931}932933impl From<CreateReFungibleData> for CreateItemData {934 fn from(item: CreateReFungibleData) -> Self {935 CreateItemData::ReFungible(item)936 }937}938939impl From<CreateFungibleData> for CreateItemData {940 fn from(item: CreateFungibleData) -> Self {941 CreateItemData::Fungible(item)942 }943}944945/// Token's address, dictated by its collection and token IDs.946#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]947#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]948// todo possibly rename to be used generally as an address pair949pub struct TokenChild {950 /// Token id.951 pub token: TokenId,952953 /// Collection id.954 pub collection: CollectionId,955}956957/// Collection statistics.958#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]959#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]960pub struct CollectionStats {961 /// Number of created items.962 pub created: u32,963964 /// Number of burned items.965 pub destroyed: u32,966967 /// Number of current items.968 pub alive: u32,969}970971/// This type works like [`PhantomData`] but supports generating _scale-info_ descriptions to generate node metadata.972#[derive(Encode, Decode, Clone, Debug)]973#[cfg_attr(feature = "std", derive(PartialEq))]974pub struct PhantomType<T>(core::marker::PhantomData<T>);975976impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {977 type Identity = PhantomType<T>;978979 fn type_info() -> scale_info::Type {980 use scale_info::{981 Type, Path,982 build::{FieldsBuilder, UnnamedFields},983 form::MetaForm,984 type_params,985 };986 Type::builder()987 .path(Path::new("up_data_structs", "PhantomType"))988 .type_params(type_params!(T))989 .composite(990 <FieldsBuilder<MetaForm, UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()),991 )992 }993}994impl<T> MaxEncodedLen for PhantomType<T> {995 fn max_encoded_len() -> usize {996 0997 }998}9991000/// Bounded vector of bytes.1001pub type BoundedBytes<S> = BoundedVec<u8, S>;10021003/// Extra properties for external collections.1004pub type AuxPropertyValue = BoundedBytes<ConstU32<MAX_AUX_PROPERTY_VALUE_LENGTH>>;10051006/// Property key.1007pub type PropertyKey = BoundedBytes<ConstU32<MAX_PROPERTY_KEY_LENGTH>>;10081009/// Property value.1010pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;10111012/// Property permission.1013#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone, Default)]1014#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1015pub struct PropertyPermission {1016 /// Permission to change the property and property permission.1017 ///1018 /// If it **false** then you can not change corresponding property even if [`collection_admin`] and [`token_owner`] are **true**.1019 pub mutable: bool,10201021 /// Change permission for the collection administrator.1022 pub collection_admin: bool,10231024 /// Permission to change the property for the owner of the token.1025 pub token_owner: bool,1026}10271028impl PropertyPermission {1029 /// Creates mutable property permission but changes restricted for collection admin and token owner.1030 pub fn none() -> Self {1031 Self {1032 mutable: true,1033 collection_admin: false,1034 token_owner: false,1035 }1036 }1037}10381039/// Property is simpl key-value record.1040#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]1041#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1042pub struct Property {1043 /// Property key.1044 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1045 pub key: PropertyKey,10461047 /// Property value.1048 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1049 pub value: PropertyValue,1050}10511052impl Into<(PropertyKey, PropertyValue)> for Property {1053 fn into(self) -> (PropertyKey, PropertyValue) {1054 (self.key, self.value)1055 }1056}10571058/// Record for proprty key permission.1059#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]1060#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1061pub struct PropertyKeyPermission {1062 /// Key.1063 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1064 pub key: PropertyKey,10651066 /// Permission.1067 pub permission: PropertyPermission,1068}10691070impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {1071 fn into(self) -> (PropertyKey, PropertyPermission) {1072 (self.key, self.permission)1073 }1074}10751076/// Errors for properties actions.1077#[derive(Debug)]1078pub enum PropertiesError {1079 /// The space allocated for properties has run out.1080 ///1081 /// * Limit for colection - [`MAX_COLLECTION_PROPERTIES_SIZE`].1082 /// * Limit for token - [`MAX_TOKEN_PROPERTIES_SIZE`].1083 NoSpaceForProperty,10841085 /// The property limit has been reached.1086 ///1087 /// * Limit - [`MAX_PROPERTIES_PER_ITEM`].1088 PropertyLimitReached,10891090 /// Property key contains not allowed character.1091 InvalidCharacterInPropertyKey,10921093 /// Property key length is too long.1094 ///1095 /// * Limit - [`MAX_PROPERTY_KEY_LENGTH`].1096 PropertyKeyIsTooLong,10971098 /// Property key is empty.1099 EmptyPropertyKey,1100}11011102/// Marker for scope of property.1103///1104/// Scoped property can't be changed by user. Used for external collections.1105#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Clone, Copy)]1106pub enum PropertyScope {1107 None,1108 Rmrk,1109}11101111impl PropertyScope {1112 /// Apply scope to property key.1113 pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {1114 let scope_str: &[u8] = match self {1115 Self::None => return Ok(key),1116 Self::Rmrk => b"rmrk",1117 };11181119 [scope_str, b":", key.as_slice()]1120 .concat()1121 .try_into()1122 .map_err(|_| PropertiesError::PropertyKeyIsTooLong)1123 }1124}11251126/// Trait for operate with properties.1127pub trait TrySetProperty: Sized {1128 type Value;11291130 /// Try to set property with scope.1131 fn try_scoped_set(1132 &mut self,1133 scope: PropertyScope,1134 key: PropertyKey,1135 value: Self::Value,1136 ) -> Result<Option<Self::Value>, PropertiesError>;11371138 /// Try to set property with scope from iterator.1139 fn try_scoped_set_from_iter<I, KV>(1140 &mut self,1141 scope: PropertyScope,1142 iter: I,1143 ) -> Result<(), PropertiesError>1144 where1145 I: Iterator<Item = KV>,1146 KV: Into<(PropertyKey, Self::Value)>,1147 {1148 for kv in iter {1149 let (key, value) = kv.into();1150 self.try_scoped_set(scope, key, value)?;1151 }11521153 Ok(())1154 }11551156 /// Try to set property.1157 fn try_set(1158 &mut self,1159 key: PropertyKey,1160 value: Self::Value,1161 ) -> Result<Option<Self::Value>, PropertiesError> {1162 self.try_scoped_set(PropertyScope::None, key, value)1163 }11641165 /// Try to set property from iterator.1166 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>1167 where1168 I: Iterator<Item = KV>,1169 KV: Into<(PropertyKey, Self::Value)>,1170 {1171 self.try_scoped_set_from_iter(PropertyScope::None, iter)1172 }1173}11741175/// Wrapped map for storing properties.1176#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]1177#[derivative(Default(bound = ""))]1178pub struct PropertiesMap<Value>(1179 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,1180);11811182impl<Value> PropertiesMap<Value> {1183 /// Create new property map.1184 pub fn new() -> Self {1185 Self(BoundedBTreeMap::new())1186 }11871188 /// Remove property from map.1189 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {1190 Self::check_property_key(key)?;11911192 Ok(self.0.remove(key))1193 }11941195 /// Get property with appropriate key from map.1196 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {1197 self.0.get(key)1198 }11991200 /// Check if map contains key.1201 pub fn contains_key(&self, key: &PropertyKey) -> bool {1202 self.0.contains_key(key)1203 }12041205 /// Check if map contains key with key validation.1206 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {1207 if key.is_empty() {1208 return Err(PropertiesError::EmptyPropertyKey);1209 }12101211 for byte in key.as_slice().iter() {1212 let byte = *byte;12131214 if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' && byte != b'.' {1215 return Err(PropertiesError::InvalidCharacterInPropertyKey);1216 }1217 }12181219 Ok(())1220 }12211222 pub fn values(&self) -> impl Iterator<Item = &Value> {1223 self.0.values()1224 }1225}12261227impl<Value> IntoIterator for PropertiesMap<Value> {1228 type Item = (PropertyKey, Value);1229 type IntoIter = <1230 BoundedBTreeMap<1231 PropertyKey,1232 Value,1233 ConstU32<MAX_PROPERTIES_PER_ITEM>1234 > as IntoIterator1235 >::IntoIter;12361237 fn into_iter(self) -> Self::IntoIter {1238 self.0.into_iter()1239 }1240}12411242impl<Value> TrySetProperty for PropertiesMap<Value> {1243 type Value = Value;12441245 fn try_scoped_set(1246 &mut self,1247 scope: PropertyScope,1248 key: PropertyKey,1249 value: Self::Value,1250 ) -> Result<Option<Self::Value>, PropertiesError> {1251 Self::check_property_key(&key)?;12521253 let key = scope.apply(key)?;1254 self.01255 .try_insert(key, value)1256 .map_err(|_| PropertiesError::PropertyLimitReached)1257 }1258}12591260/// Alias for property permissions map.1261pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;12621263/// Wrapper for properties map with consumed space control.1264#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]1265pub struct Properties {1266 map: PropertiesMap<PropertyValue>,1267 consumed_space: u32,1268 space_limit: u32,1269}12701271impl Properties {1272 /// Create new properies container.1273 pub fn new(space_limit: u32) -> Self {1274 Self {1275 map: PropertiesMap::new(),1276 consumed_space: 0,1277 space_limit,1278 }1279 }12801281 /// Remove propery with appropiate key.1282 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {1283 let value = self.map.remove(key)?;12841285 if let Some(ref value) = value {1286 let value_len = value.len() as u32;1287 self.consumed_space -= value_len;1288 }12891290 Ok(value)1291 }12921293 /// Get property with appropriate key.1294 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {1295 self.map.get(key)1296 }12971298 /// Recomputes the consumed space for the current properties state.1299 /// Needed to repair a token due to a bug fixed in the [PR #733](https://github.com/UniqueNetwork/unique-chain/pull/773).1300 pub fn recompute_consumed_space(&mut self) {1301 self.consumed_space = self.map.values().map(|value| value.len() as u32).sum();1302 }1303}13041305impl IntoIterator for Properties {1306 type Item = (PropertyKey, PropertyValue);1307 type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;13081309 fn into_iter(self) -> Self::IntoIter {1310 self.map.into_iter()1311 }1312}13131314impl TrySetProperty for Properties {1315 type Value = PropertyValue;13161317 fn try_scoped_set(1318 &mut self,1319 scope: PropertyScope,1320 key: PropertyKey,1321 value: Self::Value,1322 ) -> Result<Option<Self::Value>, PropertiesError> {1323 let value_len = value.len();13241325 if self.consumed_space as usize + value_len > self.space_limit as usize1326 && !cfg!(feature = "runtime-benchmarks")1327 {1328 return Err(PropertiesError::NoSpaceForProperty);1329 }13301331 let value_len = value_len as u32;1332 let old_value = self.map.try_scoped_set(scope, key, value)?;13331334 let old_value_len = old_value.as_ref().map(|v| v.len() as u32).unwrap_or(0);13351336 if value_len > old_value_len {1337 self.consumed_space += value_len - old_value_len;1338 } else {1339 self.consumed_space -= old_value_len - value_len;1340 }13411342 Ok(old_value)1343 }1344}13451346/// Utility struct for using in `StorageMap`.1347pub struct CollectionProperties;13481349impl Get<Properties> for CollectionProperties {1350 fn get() -> Properties {1351 Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)1352 }1353}13541355/// Utility struct for using in `StorageMap`.1356pub struct TokenProperties;13571358impl Get<Properties> for TokenProperties {1359 fn get() -> Properties {1360 Properties::new(MAX_TOKEN_PROPERTIES_SIZE)1361 }1362}13631364// RMRK1365// todo document?1366parameter_types! {1367 #[derive(PartialEq, TypeInfo)]1368 pub const RmrkStringLimit: u32 = 128;1369 #[derive(PartialEq)]1370 pub const RmrkCollectionSymbolLimit: u32 = MAX_TOKEN_PREFIX_LENGTH;1371 #[derive(PartialEq)]1372 pub const RmrkResourceSymbolLimit: u32 = 10;1373 #[derive(PartialEq)]1374 pub const RmrkBaseSymbolLimit: u32 = MAX_TOKEN_PREFIX_LENGTH;1375 #[derive(PartialEq)]1376 pub const RmrkKeyLimit: u32 = 32;1377 #[derive(PartialEq)]1378 pub const RmrkValueLimit: u32 = 256;1379 #[derive(PartialEq)]1380 pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;1381 #[derive(PartialEq)]1382 pub const MaxPropertiesPerTheme: u32 = 5;1383 #[derive(PartialEq)]1384 pub const RmrkPartsLimit: u32 = 25;1385 #[derive(PartialEq)]1386 pub const RmrkMaxPriorities: u32 = 25;1387 #[derive(PartialEq)]1388 pub const MaxResourcesOnMint: u32 = 100;1389}13901391impl From<RmrkCollectionId> for CollectionId {1392 fn from(id: RmrkCollectionId) -> Self {1393 Self(id)1394 }1395}13961397impl From<RmrkNftId> for TokenId {1398 fn from(id: RmrkNftId) -> Self {1399 Self(id)1400 }1401}14021403pub type RmrkCollectionInfo<AccountId> =1404 CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;1405pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;1406pub type RmrkResourceInfo = ResourceInfo<RmrkString, RmrkBoundedParts>;1407pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;1408pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;1409pub type BoundedEquippableCollectionIds =1410 BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>;1411pub type RmrkPartType = PartType<RmrkString, BoundedEquippableCollectionIds>;1412pub type RmrkEquippableList = EquippableList<BoundedEquippableCollectionIds>;1413pub type RmrkThemeProperty = ThemeProperty<RmrkString>;1414pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;1415pub type RmrkBoundedTheme = Theme<RmrkString, BoundedVec<RmrkThemeProperty, MaxPropertiesPerTheme>>;1416pub type RmrkResourceTypes = ResourceTypes<RmrkString, RmrkBoundedParts>;14171418pub type RmrkBasicResource = BasicResource<RmrkString>;1419pub type RmrkComposableResource = ComposableResource<RmrkString, RmrkBoundedParts>;1420pub type RmrkSlotResource = SlotResource<RmrkString>;14211422pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;1423pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;1424pub type RmrkBaseSymbol = BoundedVec<u8, RmrkBaseSymbolLimit>;1425pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;1426pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;1427pub type RmrkBoundedResource = BoundedVec<u8, RmrkResourceSymbolLimit>;1428pub type RmrkBoundedParts = BoundedVec<RmrkPartId, RmrkPartsLimit>; // todo make sure it is needed14291430pub type RmrkRpcString = Vec<u8>;1431pub type RmrkThemeName = RmrkRpcString;1432pub type RmrkPropertyKey = RmrkRpcString;tests/src/eth/tokenProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/tokenProperties.test.ts
+++ b/tests/src/eth/tokenProperties.test.ts
@@ -69,6 +69,134 @@
}));
[
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`[${testCase.mode}] Set and get multiple token property permissions as owner`, testCase.requiredPallets, async({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionId, collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+
+ await collection.methods.setTokenPropertyPermissions([
+ ['testKey_0', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ['testKey_1', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, false],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ['testKey_2', [
+ [EthTokenPermissions.Mutable, false],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, false]],
+ ],
+ ]).send({from: owner});
+
+ expect(await helper[testCase.mode].getPropertyPermissions(collectionId)).to.be.deep.equal([
+ {
+ key: 'testKey_0',
+ permission: {mutable: true, tokenOwner: true, collectionAdmin: true},
+ },
+ {
+ key: 'testKey_1',
+ permission: {mutable: true, tokenOwner: false, collectionAdmin: true},
+ },
+ {
+ key: 'testKey_2',
+ permission: {mutable: false, tokenOwner: true, collectionAdmin: false},
+ },
+ ]);
+
+ expect(await collection.methods.tokenPropertyPermissions().call({from: owner})).to.be.like([
+ ['testKey_0', [
+ [EthTokenPermissions.Mutable.toString(), true],
+ [EthTokenPermissions.TokenOwner.toString(), true],
+ [EthTokenPermissions.CollectionAdmin.toString(), true]],
+ ],
+ ['testKey_1', [
+ [EthTokenPermissions.Mutable.toString(), true],
+ [EthTokenPermissions.TokenOwner.toString(), false],
+ [EthTokenPermissions.CollectionAdmin.toString(), true]],
+ ],
+ ['testKey_2', [
+ [EthTokenPermissions.Mutable.toString(), false],
+ [EthTokenPermissions.TokenOwner.toString(), true],
+ [EthTokenPermissions.CollectionAdmin.toString(), false]],
+ ],
+ ]);
+
+ }));
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`[${testCase.mode}] Set and get multiple token property permissions as admin`, testCase.requiredPallets, async({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const caller = await helper.ethCrossAccount.createAccountWithBalance(donor);
+
+ const {collectionId, collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+ await collection.methods.addCollectionAdminCross(caller).send({from: owner});
+
+ await collection.methods.setTokenPropertyPermissions([
+ ['testKey_0', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ['testKey_1', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, false],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ['testKey_2', [
+ [EthTokenPermissions.Mutable, false],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, false]],
+ ],
+ ]).send({from: caller.eth});
+
+ expect(await helper[testCase.mode].getPropertyPermissions(collectionId)).to.be.deep.equal([
+ {
+ key: 'testKey_0',
+ permission: {mutable: true, tokenOwner: true, collectionAdmin: true},
+ },
+ {
+ key: 'testKey_1',
+ permission: {mutable: true, tokenOwner: false, collectionAdmin: true},
+ },
+ {
+ key: 'testKey_2',
+ permission: {mutable: false, tokenOwner: true, collectionAdmin: false},
+ },
+ ]);
+
+ expect(await collection.methods.tokenPropertyPermissions().call({from: caller.eth})).to.be.like([
+ ['testKey_0', [
+ [EthTokenPermissions.Mutable.toString(), true],
+ [EthTokenPermissions.TokenOwner.toString(), true],
+ [EthTokenPermissions.CollectionAdmin.toString(), true]],
+ ],
+ ['testKey_1', [
+ [EthTokenPermissions.Mutable.toString(), true],
+ [EthTokenPermissions.TokenOwner.toString(), false],
+ [EthTokenPermissions.CollectionAdmin.toString(), true]],
+ ],
+ ['testKey_2', [
+ [EthTokenPermissions.Mutable.toString(), false],
+ [EthTokenPermissions.TokenOwner.toString(), true],
+ [EthTokenPermissions.CollectionAdmin.toString(), false]],
+ ],
+ ]);
+
+ }));
+
+ [
{
method: 'setProperties',
methodParams: [[{key: 'testKey1', value: Buffer.from('testValue1')}, {key: 'testKey2', value: Buffer.from('testValue2')}]],
@@ -319,6 +447,47 @@
const actualProps = await collectionEvm.methods.properties(token.tokenId, []).call();
expect(actualProps).to.deep.eq(expectedProps);
}));
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`[${testCase.mode}] Cant set token property permissions as non owner or admin`, testCase.requiredPallets, async({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const caller = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+
+ await expect(collection.methods.setTokenPropertyPermissions([
+ ['testKey_0', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ]).call({from: caller})).to.be.rejectedWith('NoPermission');
+ }));
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`[${testCase.mode}] Cant set token property permissions with invalid character`, testCase.requiredPallets, async({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+
+ const {collectionAddress} = await helper.eth.createCollection(testCase.mode, owner, 'A', 'B', 'C');
+ const collection = await helper.ethNativeContract.collection(collectionAddress, testCase.mode, owner);
+
+ await expect(collection.methods.setTokenPropertyPermissions([
+ // "Space" is invalid character
+ ['testKey 0', [
+ [EthTokenPermissions.Mutable, true],
+ [EthTokenPermissions.TokenOwner, true],
+ [EthTokenPermissions.CollectionAdmin, true]],
+ ],
+ ]).call({from: owner})).to.be.rejectedWith('InvalidCharacterInPropertyKey');
+ }));
+
});