git.delta.rocks / unique-network / refs/commits / 0b47f7af660b

difftreelog

Merge branch 'UniqueNetwork:develop' into develop

Alex2022-08-02parents: #f46a437 #4247b84.patch.diff
in: master

4 files changed

modifiedprimitives/data-structs/src/bounded.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/bounded.rs
+++ b/primitives/data-structs/src/bounded.rs
@@ -1,3 +1,21 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+//! This module contins implementations for support bounded structures ([`BoundedVec`], [`BoundedBTreeMap`], [`BoundedBTreeSet`]) in [`serde`].
+
 use core::fmt;
 use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet};
 use sp_std::vec::Vec;
@@ -7,7 +25,7 @@
 	storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},
 };
 
-/// BoundedVec doesn't supports serde
+/// [`serde`] implementations for [`BoundedVec`].
 #[cfg(feature = "serde1")]
 pub mod vec_serde {
 	use core::convert::TryFrom;
@@ -39,6 +57,7 @@
 	}
 }
 
+/// Format [`BoundedVec`] for debug output.
 pub fn vec_debug<V, S>(v: &BoundedVec<V, S>, f: &mut fmt::Formatter) -> Result<(), fmt::Error>
 where
 	V: fmt::Debug,
@@ -49,6 +68,7 @@
 
 #[cfg(feature = "serde1")]
 #[allow(dead_code)]
+/// [`serde`] implementations for [`BoundedBTreeMap`].
 pub mod map_serde {
 	use core::convert::TryFrom;
 	use sp_std::collections::btree_map::BTreeMap;
@@ -84,6 +104,7 @@
 	}
 }
 
+/// Format [`BoundedBTreeMap`] for debug output.
 pub fn map_debug<K, V, S>(
 	v: &BoundedBTreeMap<K, V, S>,
 	f: &mut fmt::Formatter,
@@ -98,6 +119,7 @@
 
 #[cfg(feature = "serde1")]
 #[allow(dead_code)]
+/// [`serde`] implementations for [`BoundedBTreeSet`].
 pub mod set_serde {
 	use core::convert::TryFrom;
 	use sp_std::collections::btree_set::BTreeSet;
@@ -129,6 +151,7 @@
 	}
 }
 
+/// Format [`BoundedBTreeSet`] for debug output.
 pub fn set_debug<K, S>(v: &BoundedBTreeSet<K, S>, f: &mut fmt::Formatter) -> Result<(), fmt::Error>
 where
 	K: fmt::Debug + Ord,
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
14// You should have received a copy of the GNU General Public License14// You should have received a copy of the GNU General Public License
15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
16
17//! # Primitives crate.
18//!
19//! This crate contains types, traits and constants.
1620
17#![cfg_attr(not(feature = "std"), no_std)]21#![cfg_attr(not(feature = "std"), no_std)]
1822
55pub mod mapping;59pub mod mapping;
56mod migration;60mod migration;
5761
62/// Maximum of decimal points.
58pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;63pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;
64
65/// Maximum pieces for refungible token.
59pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;66pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;
60pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;67pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;
6168
69/// Maximum tokens for user.
62pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {70pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {
63 100_00071 100_000
64} else {72} else {
65 1073 10
66};74};
75
76/// Maximum for collections can be created.
67pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {77pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {
68 100_00078 100_000
69} else {79} else {
70 1080 10
71};81};
82
83/// Maximum for various custom data of token.
72pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {84pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {
73 204885 2048
74} else {86} else {
75 1087 10
76};88};
89
90/// Maximum admins per collection.
77pub const COLLECTION_ADMINS_LIMIT: u32 = 5;91pub const COLLECTION_ADMINS_LIMIT: u32 = 5;
92
93/// Maximum tokens per collection.
78pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;94pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;
95
96/// Maximum tokens per account.
79pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {97pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {
80 1_000_00098 1_000_000
81} else {99} else {
82 10100 10
83};101};
84102
85// Timeouts for item types in passed blocks103/// Default timeout for transfer sponsoring NFT item.
86pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;104pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;
105/// Default timeout for transfer sponsoring fungible item.
87pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;106pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;
107/// Default timeout for transfer sponsoring refungible item.
88pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;108pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;
89109
110/// Default timeout for sponsored approving.
90pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;111pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;
91112
92// Schema limits113// Schema limits
93pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;114pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;
94pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;115pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;
95pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;116pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;
96117
118// TODO: not used. Delete?
97pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;119pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;
98120
121/// Maximum length for collection name.
99pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;122pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;
123
124/// Maximum length for collection description.
100pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;125pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;
126
127/// Maximal token prefix length.
101pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;128pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;
102129
130/// Maximal lenght of property key.
103pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;131pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;
132
133/// Maximal lenght of property value.
104pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;134pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;
135
136/// Maximum properties that can be assigned to token.
105pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;137pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;
106138
139/// Maximal lenght of extended property value.
107pub const MAX_AUX_PROPERTY_VALUE_LENGTH: u32 = 2048;140pub const MAX_AUX_PROPERTY_VALUE_LENGTH: u32 = 2048;
108141
142/// Maximum size for all collection properties.
109pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;143pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;
144
145/// Maximum size for all token properties.
110pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;146pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;
111147
112/// How much items can be created per single148/// How much items can be created per single
113/// create_many call149/// create_many call.
114pub const MAX_ITEMS_PER_BATCH: u32 = 200;150pub const MAX_ITEMS_PER_BATCH: u32 = 200;
115151
152/// Used for limit bounded types of token custom data.
116pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;153pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;
117154
155/// Collection id.
118#[derive(156#[derive(
119 Encode,157 Encode,
120 Decode,158 Decode,
134impl EncodeLike<u32> for CollectionId {}172impl EncodeLike<u32> for CollectionId {}
135impl EncodeLike<CollectionId> for u32 {}173impl EncodeLike<CollectionId> for u32 {}
136174
175/// Token id.
137#[derive(176#[derive(
138 Encode,177 Encode,
139 Decode,178 Decode,
154impl EncodeLike<TokenId> for u32 {}193impl EncodeLike<TokenId> for u32 {}
155194
156impl TokenId {195impl TokenId {
196 /// Try to get next token id.
197 ///
198 /// If next id cause overflow, then [`ArithmeticError::Overflow`] returned.
157 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {199 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {
158 self.0200 self.0
159 .checked_add(1)201 .checked_add(1)
176 }218 }
177}219}
178220
221/// Token data.
179#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]222#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
180#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]223#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
181pub struct TokenData<CrossAccountId> {224pub struct TokenData<CrossAccountId> {
225 /// Properties of token.
182 pub properties: Vec<Property>,226 pub properties: Vec<Property>,
227
228 /// Token owner.
183 pub owner: Option<CrossAccountId>,229 pub owner: Option<CrossAccountId>,
230
231 /// Token pieces.
184 pub pieces: u128,232 pub pieces: u128,
185}233}
186234
235// TODO: unused type
187pub struct OverflowError;236pub struct OverflowError;
188impl From<OverflowError> for &'static str {237impl From<OverflowError> for &'static str {
189 fn from(_: OverflowError) -> Self {238 fn from(_: OverflowError) -> Self {
190 "overflow occured"239 "overflow occured"
191 }240 }
192}241}
193242
243/// Alias for decimal points type.
194pub type DecimalPoints = u8;244pub type DecimalPoints = u8;
195245
246/// Collection mode.
247///
248/// Collection can represent various types of tokens.
249/// Each collection can contain only one type of tokens at a time.
250/// This type helps to understand which tokens the collection contains.
196#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]251#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
197#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]252#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
198pub enum CollectionMode {253pub enum CollectionMode {
254 /// Non fungible tokens.
199 NFT,255 NFT,
256 /// Fungible tokens.
200 Fungible(DecimalPoints),257 Fungible(DecimalPoints),
258 /// Refungible tokens.
201 ReFungible,259 ReFungible,
202}260}
203261
204impl CollectionMode {262impl CollectionMode {
263 /// Get collection mod as number.
205 pub fn id(&self) -> u8 {264 pub fn id(&self) -> u8 {
206 match self {265 match self {
207 CollectionMode::NFT => 1,266 CollectionMode::NFT => 1,
211 }270 }
212}271}
213272
273// TODO: unused trait
214pub trait SponsoringResolve<AccountId, Call> {274pub trait SponsoringResolve<AccountId, Call> {
215 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;275 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;
216}276}
217277
278/// Access mode for some token operations.
218#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]279#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]
219#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]280#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
220pub enum AccessMode {281pub enum AccessMode {
282 /// Access grant for owner and admins. Used as default.
221 Normal,283 Normal,
284 /// Like a [`Normal`](AccessMode::Normal) but also users in allow list.
222 AllowList,285 AllowList,
223}286}
224impl Default for AccessMode {287impl Default for AccessMode {
227 }290 }
228}291}
229292
293// TODO: remove in future.
230#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]294#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
231#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]295#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
232pub enum SchemaVersion {296pub enum SchemaVersion {
239 }303 }
240}304}
241305
306// TODO: unused type
242#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]307#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]
243#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]308#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
244pub struct Ownership<AccountId> {309pub struct Ownership<AccountId> {
245 pub owner: AccountId,310 pub owner: AccountId,
246 pub fraction: u128,311 pub fraction: u128,
247}312}
248313
314/// The state of collection sponsorship.
249#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]315#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
250#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]316#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
251pub enum SponsorshipState<AccountId> {317pub enum SponsorshipState<AccountId> {
252 /// The fees are applied to the transaction sender318 /// The fees are applied to the transaction sender.
253 Disabled,319 Disabled,
254 /// Pending confirmation from a sponsor-to-be320 /// The sponsor is under consideration. Until the sponsor gives his consent,
321 /// the fee will still be charged to sender.
255 Unconfirmed(AccountId),322 Unconfirmed(AccountId),
256 /// Transactions are sponsored by specified account323 /// Transactions are sponsored by specified account.
257 Confirmed(AccountId),324 Confirmed(AccountId),
258}325}
259326
260impl<AccountId> SponsorshipState<AccountId> {327impl<AccountId> SponsorshipState<AccountId> {
261 /// Get the acting sponsor account, if present328 /// Get a sponsor of the collection who has confirmed his status.
262 pub fn sponsor(&self) -> Option<&AccountId> {329 pub fn sponsor(&self) -> Option<&AccountId> {
263 match self {330 match self {
264 Self::Confirmed(sponsor) => Some(sponsor),331 Self::Confirmed(sponsor) => Some(sponsor),
265 _ => None,332 _ => None,
266 }333 }
267 }334 }
268335
269 /// Get the sponsor account currently pending confirmation, if present336 /// Get a sponsor of the collection who has pending or confirmed status.
270 pub fn pending_sponsor(&self) -> Option<&AccountId> {337 pub fn pending_sponsor(&self) -> Option<&AccountId> {
271 match self {338 match self {
272 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),339 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),
273 _ => None,340 _ => None,
274 }341 }
275 }342 }
276343
277 /// Is sponsorship set and acting344 /// Whether the sponsorship is confirmed.
278 pub fn confirmed(&self) -> bool {345 pub fn confirmed(&self) -> bool {
279 matches!(self, Self::Confirmed(_))346 matches!(self, Self::Confirmed(_))
280 }347 }
290pub type CollectionDescription = BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>;357pub type CollectionDescription = BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>;
291pub type CollectionTokenPrefix = BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>;358pub type CollectionTokenPrefix = BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>;
292359
360/// Base structure for represent collection.
361///
362/// Used to provide basic functionality for all types of collections.
363///
364/// #### Note
293/// Collection parameters, used in storage (see [`RpcCollection`] for the RPC version).365/// Collection parameters, used in storage (see [`RpcCollection`] for the RPC version).
294#[struct_versioning::versioned(version = 2, upper)]366#[struct_versioning::versioned(version = 2, upper)]
295#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]367#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
296pub struct Collection<AccountId> {368pub struct Collection<AccountId> {
369 /// Collection owner account.
297 pub owner: AccountId,370 pub owner: AccountId,
371
372 /// Collection mode.
298 pub mode: CollectionMode,373 pub mode: CollectionMode,
374
375 /// Access mode.
299 #[version(..2)]376 #[version(..2)]
300 pub access: AccessMode,377 pub access: AccessMode,
378
379 /// Collection name.
301 pub name: CollectionName,380 pub name: CollectionName,
381
382 /// Collection description.
302 pub description: CollectionDescription,383 pub description: CollectionDescription,
384
385 /// Token prefix.
303 pub token_prefix: CollectionTokenPrefix,386 pub token_prefix: CollectionTokenPrefix,
304387
305 #[version(..2)]388 #[version(..2)]
311 #[version(..2)]394 #[version(..2)]
312 pub schema_version: SchemaVersion,395 pub schema_version: SchemaVersion,
396
397 /// The state of sponsorship of the collection.
313 pub sponsorship: SponsorshipState<AccountId>,398 pub sponsorship: SponsorshipState<AccountId>,
314399
400 /// Collection limits.
315 pub limits: CollectionLimits,401 pub limits: CollectionLimits,
316402
403 /// Collection permissions.
317 #[version(2.., upper(Default::default()))]404 #[version(2.., upper(Default::default()))]
318 pub permissions: CollectionPermissions,405 pub permissions: CollectionPermissions,
319406
335#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]422#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
336#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]423#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
337pub struct RpcCollection<AccountId> {424pub struct RpcCollection<AccountId> {
425 /// Collection owner account.
338 pub owner: AccountId,426 pub owner: AccountId,
427
428 /// Collection mode.
339 pub mode: CollectionMode,429 pub mode: CollectionMode,
430
431 /// Collection name.
340 pub name: Vec<u16>,432 pub name: Vec<u16>,
433
434 /// Collection description.
341 pub description: Vec<u16>,435 pub description: Vec<u16>,
436
437 /// Token prefix.
342 pub token_prefix: Vec<u8>,438 pub token_prefix: Vec<u8>,
439
440 /// The state of sponsorship of the collection.
343 pub sponsorship: SponsorshipState<AccountId>,441 pub sponsorship: SponsorshipState<AccountId>,
442
443 /// Collection limits.
344 pub limits: CollectionLimits,444 pub limits: CollectionLimits,
445
446 /// Collection permissions.
345 pub permissions: CollectionPermissions,447 pub permissions: CollectionPermissions,
448
449 /// Token property permissions.
346 pub token_property_permissions: Vec<PropertyKeyPermission>,450 pub token_property_permissions: Vec<PropertyKeyPermission>,
451
452 /// Collection properties.
347 pub properties: Vec<Property>,453 pub properties: Vec<Property>,
454
455 /// Is collection read only.
348 pub read_only: bool,456 pub read_only: bool,
349}457}
350458
459/// Data used for create collection.
460///
461/// All fields are wrapped in [`Option`], where `None` means chain default.
351#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]462#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]
352#[derivative(Debug, Default(bound = ""))]463#[derivative(Debug, Default(bound = ""))]
353pub struct CreateCollectionData<AccountId> {464pub struct CreateCollectionData<AccountId> {
465 /// Collection mode.
354 #[derivative(Default(value = "CollectionMode::NFT"))]466 #[derivative(Default(value = "CollectionMode::NFT"))]
355 pub mode: CollectionMode,467 pub mode: CollectionMode,
468
469 /// Access mode.
356 pub access: Option<AccessMode>,470 pub access: Option<AccessMode>,
471
472 /// Collection name.
357 pub name: CollectionName,473 pub name: CollectionName,
474
475 /// Collection description.
358 pub description: CollectionDescription,476 pub description: CollectionDescription,
477
478 /// Token prefix.
359 pub token_prefix: CollectionTokenPrefix,479 pub token_prefix: CollectionTokenPrefix,
480
481 /// Pending collection sponsor.
360 pub pending_sponsor: Option<AccountId>,482 pub pending_sponsor: Option<AccountId>,
483
484 /// Collection limits.
361 pub limits: Option<CollectionLimits>,485 pub limits: Option<CollectionLimits>,
486
487 /// Collection permissions.
362 pub permissions: Option<CollectionPermissions>,488 pub permissions: Option<CollectionPermissions>,
489
490 /// Token property permissions.
363 pub token_property_permissions: CollectionPropertiesPermissionsVec,491 pub token_property_permissions: CollectionPropertiesPermissionsVec,
492
493 /// Collection properties.
364 pub properties: CollectionPropertiesVec,494 pub properties: CollectionPropertiesVec,
365}495}
366496
497/// Bounded vector of properties permissions. Max length is [`MAX_PROPERTIES_PER_ITEM`].
498// TODO: maybe rename to PropertiesPermissionsVec
367pub type CollectionPropertiesPermissionsVec =499pub type CollectionPropertiesPermissionsVec =
368 BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;500 BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
369501
502/// Bounded vector of properties. Max length is [`MAX_PROPERTIES_PER_ITEM`].
370pub type CollectionPropertiesVec = BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;503pub type CollectionPropertiesVec = BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
371504
372/// Limits and restrictions of a collection.505/// Limits and restrictions of a collection.
506///
373/// All fields are wrapped in `Option`s, where None means chain default.507/// All fields are wrapped in [`Option`], where `None` means chain default.
374///508///
375/// todo:doc links to chain defaults509/// Update with `pallet_common::Pallet::clamp_limits`.
376// IMPORTANT: When adding/removing fields from this struct - don't forget to also510// IMPORTANT: When adding/removing fields from this struct - don't forget to also
377// update clamp_limits() in pallet-common.
378#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]511#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
379#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]512#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
513// When adding/removing fields from this struct - don't forget to also update with `pallet_common::Pallet::clamp_limits`.
514// TODO: move `pallet_common::Pallet::clamp_limits` into `impl CollectionLimits`.
515// TODO: may be remove [`Option`] and **pub** from fields and create struct with default values.
380pub struct CollectionLimits {516pub struct CollectionLimits {
381 /// Maximum number of owned tokens per account. Chain default: [`ACCOUNT_TOKEN_OWNERSHIP_LIMIT`]517 /// How many tokens can a user have on one account.
518 /// * Default - [`ACCOUNT_TOKEN_OWNERSHIP_LIMIT`].
519 /// * Limit - [`MAX_TOKEN_OWNERSHIP`].
382 pub account_token_ownership_limit: Option<u32>,520 pub account_token_ownership_limit: Option<u32>,
383 /// Maximum size of data in bytes of a sponsored transaction. Chain default: [`CUSTOM_DATA_LIMIT`]521
522 /// How many bytes of data are available for sponsorship.
523 /// * Default - [`CUSTOM_DATA_LIMIT`].
524 /// * Limit - [`CUSTOM_DATA_LIMIT`].
384 pub sponsored_data_size: Option<u32>,525 pub sponsored_data_size: Option<u32>,
385526
386 /// FIXME should we delete this or repurpose it?527 // FIXME should we delete this or repurpose it?
387 /// None - setVariableMetadata is not sponsored528 /// Times in how many blocks we sponsor data.
388 /// Some(v) - setVariableMetadata is sponsored529 ///
389 /// if there is v block between txs530 /// If is `Some(v)` then **setVariableMetadata** is sponsored if there is `v` block between transactions.
531 ///
532 /// * Default - [`SponsoringDisabled`](SponsoringRateLimit::SponsoringDisabled).
533 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].
390 ///534 ///
391 /// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]535 /// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]
392 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,536 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,
393 /// Maximum amount of tokens inside the collection. Chain default: [`COLLECTION_TOKEN_LIMIT`]537 /// Maximum amount of tokens inside the collection. Chain default: [`COLLECTION_TOKEN_LIMIT`]
538
539 /// How many tokens can be mined into this collection.
540 ///
541 /// * Default - [`COLLECTION_TOKEN_LIMIT`].
542 /// * Limit - [`COLLECTION_TOKEN_LIMIT`].
394 pub token_limit: Option<u32>,543 pub token_limit: Option<u32>,
395544
396 /// Timeout for sponsoring a token transfer in passed blocks. Chain default:545 /// Timeouts for transfer sponsoring.
397 /// either [`NFT_SPONSOR_TRANSFER_TIMEOUT`], [`FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`], or [`REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`],546 ///
398 /// depending on the collection type.547 /// * Default
548 /// - **Fungible** - [`FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`]
549 /// - **NFT** - [`NFT_SPONSOR_TRANSFER_TIMEOUT`]
550 /// - **Refungible** - [`REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`]
551 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].
399 pub sponsor_transfer_timeout: Option<u32>,552 pub sponsor_transfer_timeout: Option<u32>,
553
400 /// Timeout for sponsoring an approval in passed blocks. Chain default: [`SPONSOR_APPROVE_TIMEOUT`]554 /// Timeout for sponsoring an approval in passed blocks.
555 ///
556 /// * Default - [`SPONSOR_APPROVE_TIMEOUT`].
557 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].
401 pub sponsor_approve_timeout: Option<u32>,558 pub sponsor_approve_timeout: Option<u32>,
402 /// Can a token be transferred by the owner. Chain default: `false`559
560 /// Whether the collection owner of the collection can send tokens (which belong to other users).
561 ///
562 /// * Default - **false**.
403 pub owner_can_transfer: Option<bool>,563 pub owner_can_transfer: Option<bool>,
404 /// Can a token be burned by the owner. Chain default: `true`564
565 /// Can the collection owner burn other people's tokens.
566 ///
567 /// * Default - **true**.
405 pub owner_can_destroy: Option<bool>,568 pub owner_can_destroy: Option<bool>,
406 /// Can a token be transferred at all. Chain default: `true`569
570 /// Is it possible to send tokens from this collection between users.
571 ///
572 /// * Default - **true**.
407 pub transfers_enabled: Option<bool>,573 pub transfers_enabled: Option<bool>,
408}574}
409575
410impl CollectionLimits {576impl CollectionLimits {
577 /// Get effective value for [`account_token_ownership_limit`](self.account_token_ownership_limit).
411 pub fn account_token_ownership_limit(&self) -> u32 {578 pub fn account_token_ownership_limit(&self) -> u32 {
412 self.account_token_ownership_limit579 self.account_token_ownership_limit
413 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)580 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)
414 .min(MAX_TOKEN_OWNERSHIP)581 .min(MAX_TOKEN_OWNERSHIP)
415 }582 }
583
584 /// Get effective value for [`sponsored_data_size`](self.sponsored_data_size).
416 pub fn sponsored_data_size(&self) -> u32 {585 pub fn sponsored_data_size(&self) -> u32 {
417 self.sponsored_data_size586 self.sponsored_data_size
418 .unwrap_or(CUSTOM_DATA_LIMIT)587 .unwrap_or(CUSTOM_DATA_LIMIT)
419 .min(CUSTOM_DATA_LIMIT)588 .min(CUSTOM_DATA_LIMIT)
420 }589 }
590
591 /// Get effective value for [`token_limit`](self.token_limit).
421 pub fn token_limit(&self) -> u32 {592 pub fn token_limit(&self) -> u32 {
422 self.token_limit593 self.token_limit
423 .unwrap_or(COLLECTION_TOKEN_LIMIT)594 .unwrap_or(COLLECTION_TOKEN_LIMIT)
424 .min(COLLECTION_TOKEN_LIMIT)595 .min(COLLECTION_TOKEN_LIMIT)
425 }596 }
597
598 // TODO: may be replace u32 to mode?
599 /// Get effective value for [`sponsor_transfer_timeout`](self.sponsor_transfer_timeout).
426 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {600 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {
427 self.sponsor_transfer_timeout601 self.sponsor_transfer_timeout
428 .unwrap_or(default)602 .unwrap_or(default)
429 .min(MAX_SPONSOR_TIMEOUT)603 .min(MAX_SPONSOR_TIMEOUT)
430 }604 }
605
606 /// Get effective value for [`sponsor_approve_timeout`](self.sponsor_approve_timeout).
431 pub fn sponsor_approve_timeout(&self) -> u32 {607 pub fn sponsor_approve_timeout(&self) -> u32 {
432 self.sponsor_approve_timeout608 self.sponsor_approve_timeout
433 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)609 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)
434 .min(MAX_SPONSOR_TIMEOUT)610 .min(MAX_SPONSOR_TIMEOUT)
435 }611 }
612
613 /// Get effective value for [`owner_can_transfer`](self.owner_can_transfer).
436 pub fn owner_can_transfer(&self) -> bool {614 pub fn owner_can_transfer(&self) -> bool {
437 self.owner_can_transfer.unwrap_or(false)615 self.owner_can_transfer.unwrap_or(false)
438 }616 }
617
618 /// Get effective value for [`owner_can_transfer_instaled`](self.owner_can_transfer_instaled).
439 pub fn owner_can_transfer_instaled(&self) -> bool {619 pub fn owner_can_transfer_instaled(&self) -> bool {
440 self.owner_can_transfer.is_some()620 self.owner_can_transfer.is_some()
441 }621 }
622
623 /// Get effective value for [`owner_can_destroy`](self.owner_can_destroy).
442 pub fn owner_can_destroy(&self) -> bool {624 pub fn owner_can_destroy(&self) -> bool {
443 self.owner_can_destroy.unwrap_or(true)625 self.owner_can_destroy.unwrap_or(true)
444 }626 }
627
628 /// Get effective value for [`transfers_enabled`](self.transfers_enabled).
445 pub fn transfers_enabled(&self) -> bool {629 pub fn transfers_enabled(&self) -> bool {
446 self.transfers_enabled.unwrap_or(true)630 self.transfers_enabled.unwrap_or(true)
447 }631 }
632
633 /// Get effective value for [`sponsored_data_rate_limit`](self.sponsored_data_rate_limit).
448 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {634 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {
449 match self635 match self
450 .sponsored_data_rate_limit636 .sponsored_data_rate_limit
457}643}
458644
459/// Permissions on certain operations within a collection.645/// Permissions on certain operations within a collection.
646///
460/// All fields are wrapped in `Option`s, where None means chain default.647/// Some fields are wrapped in [`Option`], where `None` means chain default.
461// IMPORTANT: When adding/removing fields from this struct - don't forget to also648///
462// update clamp_limits() in pallet-common.649/// Update with `pallet_common::Pallet::clamp_permissions`.
463#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]650#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
464#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]651#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
652// When adding/removing fields from this struct - don't forget to also update `pallet_common::Pallet::clamp_permissions`.
653// TODO: move `pallet_common::Pallet::clamp_permissions` into `impl CollectionPermissions`.
465pub struct CollectionPermissions {654pub struct CollectionPermissions {
655 /// Access mode.
656 ///
657 /// * Default - [`AccessMode::Normal`].
466 pub access: Option<AccessMode>,658 pub access: Option<AccessMode>,
659
660 /// Minting allowance.
661 ///
662 /// * Default - **false**.
467 pub mint_mode: Option<bool>,663 pub mint_mode: Option<bool>,
664
665 /// Permissions for nesting.
666 ///
667 /// * Default
668 /// - `token_owner` - **false**
669 /// - `collection_admin` - **false**
670 /// - `restricted` - **None**
468 pub nesting: Option<NestingPermissions>,671 pub nesting: Option<NestingPermissions>,
469}672}
470673
471impl CollectionPermissions {674impl CollectionPermissions {
675 /// Get effective value for [`access`](self.access).
472 pub fn access(&self) -> AccessMode {676 pub fn access(&self) -> AccessMode {
473 self.access.unwrap_or(AccessMode::Normal)677 self.access.unwrap_or(AccessMode::Normal)
474 }678 }
679
680 /// Get effective value for [`mint_mode`](self.mint_mode).
475 pub fn mint_mode(&self) -> bool {681 pub fn mint_mode(&self) -> bool {
476 self.mint_mode.unwrap_or(false)682 self.mint_mode.unwrap_or(false)
477 }683 }
684
685 /// Get effective value for [`nesting`](self.nesting).
478 pub fn nesting(&self) -> &NestingPermissions {686 pub fn nesting(&self) -> &NestingPermissions {
479 static DEFAULT: NestingPermissions = NestingPermissions {687 static DEFAULT: NestingPermissions = NestingPermissions {
480 token_owner: false,688 token_owner: false,
487 }695 }
488}696}
489697
698/// Inner set for collections allowed to nest.
490type OwnerRestrictedSetInner = BoundedBTreeSet<CollectionId, ConstU32<16>>;699type OwnerRestrictedSetInner = BoundedBTreeSet<CollectionId, ConstU32<16>>;
491700
701/// Wraper for collections set allowing nest.
492#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]702#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]
493#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]703#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
494#[derivative(Debug)]704#[derivative(Debug)]
499);709);
710
500impl OwnerRestrictedSet {711impl OwnerRestrictedSet {
712 /// Create new set.
501 pub fn new() -> Self {713 pub fn new() -> Self {
502 Self(Default::default())714 Self(Default::default())
503 }715 }
519#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]731#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
520#[derivative(Debug)]732#[derivative(Debug)]
521pub struct NestingPermissions {733pub struct NestingPermissions {
522 /// Owner of token can nest tokens under it734 /// Owner of token can nest tokens under it.
523 pub token_owner: bool,735 pub token_owner: bool,
524 /// Admin of token collection can nest tokens under token736 /// Admin of token collection can nest tokens under token.
525 pub collection_admin: bool,737 pub collection_admin: bool,
526 /// If set - only tokens from specified collections can be nested738 /// If set - only tokens from specified collections can be nested.
527 pub restricted: Option<OwnerRestrictedSet>,739 pub restricted: Option<OwnerRestrictedSet>,
528740
529 #[cfg(feature = "runtime-benchmarks")]741 #[cfg(feature = "runtime-benchmarks")]
530 /// Anyone can nest tokens, mutually exclusive with `token_owner`, `admin`742 /// Anyone can nest tokens, mutually exclusive with `token_owner`, `admin`.
531 pub permissive: bool,743 pub permissive: bool,
532}744}
533745
534/// Enum denominating how often can sponsoring occur if it is enabled.746/// Enum denominating how often can sponsoring occur if it is enabled.
747///
748/// Used for [`collection limits`](CollectionLimits).
535#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]749#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]
536#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]750#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
537pub enum SponsoringRateLimit {751pub enum SponsoringRateLimit {
549 /// Key-value pairs used to describe the token as metadata763 /// Key-value pairs used to describe the token as metadata
550 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]764 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
551 #[derivative(Debug(format_with = "bounded::vec_debug"))]765 #[derivative(Debug(format_with = "bounded::vec_debug"))]
766 /// Properties that wil be assignet to created item.
552 pub properties: CollectionPropertiesVec,767 pub properties: CollectionPropertiesVec,
553}768}
554769
570 #[derivative(Debug(format_with = "bounded::vec_debug"))]785 #[derivative(Debug(format_with = "bounded::vec_debug"))]
571 pub const_data: BoundedVec<u8, CustomDataLimit>,786 pub const_data: BoundedVec<u8, CustomDataLimit>,
572787
573 /// Number of pieces the RFT is split into788 /// Pieces of created token.
574 pub pieces: u128,789 pub pieces: u128,
575790
576 /// Key-value pairs used to describe the token as metadata791 /// Key-value pairs used to describe the token as metadata
579 pub properties: CollectionPropertiesVec,794 pub properties: CollectionPropertiesVec,
580}795}
581796
797// TODO: remove this.
582#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]798#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
583#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]799#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
584pub enum MetaUpdatePermission {800pub enum MetaUpdatePermission {
588}804}
589805
590/// Enum holding data used for creation of all three item types.806/// Enum holding data used for creation of all three item types.
807/// Unified data for create item.
591#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]808#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
592#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]809#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
593pub enum CreateItemData {810pub enum CreateItemData {
811 /// Data for create NFT.
594 NFT(CreateNftData),812 NFT(CreateNftData),
813 /// Data for create Fungible item.
595 Fungible(CreateFungibleData),814 Fungible(CreateFungibleData),
815 /// Data for create ReFungible item.
596 ReFungible(CreateReFungibleData),816 ReFungible(CreateReFungibleData),
597}817}
598818
599/// Explicit NFT creation data with meta parameters.819/// Extended data for create NFT.
600#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]820#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]
601#[derivative(Debug)]821#[derivative(Debug)]
602pub struct CreateNftExData<CrossAccountId> {822pub struct CreateNftExData<CrossAccountId> {
823 /// Properties that wil be assignet to created item.
603 #[derivative(Debug(format_with = "bounded::vec_debug"))]824 #[derivative(Debug(format_with = "bounded::vec_debug"))]
604 pub properties: CollectionPropertiesVec,825 pub properties: CollectionPropertiesVec,
826
827 /// Owner of creating item.
605 pub owner: CrossAccountId,828 pub owner: CrossAccountId,
606}829}
607830
608/// Explicit RFT creation data with meta parameters.831/// Extended data for create ReFungible item.
609#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]832#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]
610#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]833#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]
611pub struct CreateRefungibleExData<CrossAccountId> {834pub struct CreateRefungibleExData<CrossAccountId> {
835 /// Custom data stored in token.
612 #[derivative(Debug(format_with = "bounded::vec_debug"))]836 #[derivative(Debug(format_with = "bounded::vec_debug"))]
613 pub const_data: BoundedVec<u8, CustomDataLimit>,837 pub const_data: BoundedVec<u8, CustomDataLimit>,
838
839 /// Users who will be assigned the specified number of token parts.
614 #[derivative(Debug(format_with = "bounded::map_debug"))]840 #[derivative(Debug(format_with = "bounded::map_debug"))]
615 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,841 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,
616 #[derivative(Debug(format_with = "bounded::vec_debug"))]842 #[derivative(Debug(format_with = "bounded::vec_debug"))]
617 pub properties: CollectionPropertiesVec,843 pub properties: CollectionPropertiesVec,
618}844}
619845
620/// Explicit item creation data with meta parameters, namely the owner.846/// Unified extended data for creating item.
621#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]847#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]
622#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]848#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]
623pub enum CreateItemExData<CrossAccountId> {849pub enum CreateItemExData<CrossAccountId> {
850 /// Extended data for create NFT.
624 NFT(851 NFT(
625 #[derivative(Debug(format_with = "bounded::vec_debug"))]852 #[derivative(Debug(format_with = "bounded::vec_debug"))]
626 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,853 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,
627 ),854 ),
855
856 /// Extended data for create Fungible item.
628 Fungible(857 Fungible(
629 #[derivative(Debug(format_with = "bounded::map_debug"))]858 #[derivative(Debug(format_with = "bounded::map_debug"))]
630 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,859 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,
631 ),860 ),
861
862 /// Extended data for create ReFungible item in case of
632 /// Many tokens, each may have only one owner863 /// many tokens, each may have only one owner
633 RefungibleMultipleItems(864 RefungibleMultipleItems(
634 #[derivative(Debug(format_with = "bounded::vec_debug"))]865 #[derivative(Debug(format_with = "bounded::vec_debug"))]
635 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,866 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,
636 ),867 ),
868
869 /// Extended data for create ReFungible item in case of
637 /// Single token, which may have many owners870 /// single token, which may have many owners
638 RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),871 RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),
639}872}
640873
641impl CreateItemData {874impl CreateItemData {
875 /// Get size of custom data.
642 pub fn data_size(&self) -> usize {876 pub fn data_size(&self) -> usize {
643 match self {877 match self {
644 CreateItemData::ReFungible(data) => data.const_data.len(),878 CreateItemData::ReFungible(data) => data.const_data.len(),
670#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]904#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
671// todo possibly rename to be used generally as an address pair905// todo possibly rename to be used generally as an address pair
672pub struct TokenChild {906pub struct TokenChild {
907 /// Token id.
673 pub token: TokenId,908 pub token: TokenId,
909
910 /// Collection id.
674 pub collection: CollectionId,911 pub collection: CollectionId,
675}912}
676913
914/// Collection statistics.
677#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]915#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
678#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]916#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
679pub struct CollectionStats {917pub struct CollectionStats {
918 /// Number of created items.
680 pub created: u32,919 pub created: u32,
920
921 /// Number of burned items.
681 pub destroyed: u32,922 pub destroyed: u32,
923
924 /// Number of current items.
682 pub alive: u32,925 pub alive: u32,
683}926}
684927
928/// This type works like [`PhantomData`] but supports generating _scale-info_ descriptions to generate node metadata.
685#[derive(Encode, Decode, Clone, Debug)]929#[derive(Encode, Decode, Clone, Debug)]
686#[cfg_attr(feature = "std", derive(PartialEq))]930#[cfg_attr(feature = "std", derive(PartialEq))]
687pub struct PhantomType<T>(core::marker::PhantomData<T>);931pub struct PhantomType<T>(core::marker::PhantomData<T>);
707 }951 }
708}952}
709953
954/// Bounded vector of bytes.
710pub type BoundedBytes<S> = BoundedVec<u8, S>;955pub type BoundedBytes<S> = BoundedVec<u8, S>;
711956
957/// Extra properties for external collections.
712pub type AuxPropertyValue = BoundedBytes<ConstU32<MAX_AUX_PROPERTY_VALUE_LENGTH>>;958pub type AuxPropertyValue = BoundedBytes<ConstU32<MAX_AUX_PROPERTY_VALUE_LENGTH>>;
713959
960/// Property key.
714pub type PropertyKey = BoundedBytes<ConstU32<MAX_PROPERTY_KEY_LENGTH>>;961pub type PropertyKey = BoundedBytes<ConstU32<MAX_PROPERTY_KEY_LENGTH>>;
962
963/// Property value.
715pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;964pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;
716965
966/// Property permission.
717#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]967#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]
718#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]968#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
719pub struct PropertyPermission {969pub struct PropertyPermission {
970 /// Permission to change the property and property permission.
971 ///
972 /// If it **false** then you can not change corresponding property even if [`collection_admin`] and [`token_owner`] are **true**.
720 pub mutable: bool,973 pub mutable: bool,
974
975 /// Change permission for the collection administrator.
721 pub collection_admin: bool,976 pub collection_admin: bool,
977
978 /// Permission to change the property for the owner of the token.
722 pub token_owner: bool,979 pub token_owner: bool,
723}980}
724981
725impl PropertyPermission {982impl PropertyPermission {
983 /// Creates mutable property permission but changes restricted for collection admin and token owner.
726 pub fn none() -> Self {984 pub fn none() -> Self {
727 Self {985 Self {
728 mutable: true,986 mutable: true,
732 }990 }
733}991}
734992
993/// Property is simpl key-value record.
735#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]994#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]
736#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]995#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
737pub struct Property {996pub struct Property {
997 /// Property key.
738 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]998 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
739 pub key: PropertyKey,999 pub key: PropertyKey,
7401000
1001 /// Property value.
741 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1002 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
742 pub value: PropertyValue,1003 pub value: PropertyValue,
743}1004}
748 }1009 }
749}1010}
7501011
1012/// Record for proprty key permission.
751#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]1013#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]
752#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1014#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
753pub struct PropertyKeyPermission {1015pub struct PropertyKeyPermission {
1016 /// Key.
754 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1017 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
755 pub key: PropertyKey,1018 pub key: PropertyKey,
7561019
1020 /// Permission.
757 pub permission: PropertyPermission,1021 pub permission: PropertyPermission,
758}1022}
7591023
763 }1027 }
764}1028}
7651029
1030/// Errors for properties actions.
766#[derive(Debug)]1031#[derive(Debug)]
767pub enum PropertiesError {1032pub enum PropertiesError {
1033 /// The space allocated for properties has run out.
1034 ///
1035 /// * Limit for colection - [`MAX_COLLECTION_PROPERTIES_SIZE`].
1036 /// * Limit for token - [`MAX_TOKEN_PROPERTIES_SIZE`].
768 NoSpaceForProperty,1037 NoSpaceForProperty,
1038
1039 /// The property limit has been reached.
1040 ///
1041 /// * Limit - [`MAX_PROPERTIES_PER_ITEM`].
769 PropertyLimitReached,1042 PropertyLimitReached,
1043
1044 /// Property key contains not allowed character.
770 InvalidCharacterInPropertyKey,1045 InvalidCharacterInPropertyKey,
1046
1047 /// Property key length is too long.
1048 ///
1049 /// * Limit - [`MAX_PROPERTY_KEY_LENGTH`].
771 PropertyKeyIsTooLong,1050 PropertyKeyIsTooLong,
1051
1052 /// Property key is empty.
772 EmptyPropertyKey,1053 EmptyPropertyKey,
773}1054}
7741055
1056/// Marker for scope of property.
1057///
1058/// Scoped property can't be changed by user. Used for external collections.
775#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Clone, Copy)]1059#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Clone, Copy)]
776pub enum PropertyScope {1060pub enum PropertyScope {
777 None,1061 None,
778 Rmrk,1062 Rmrk,
779}1063}
7801064
781impl PropertyScope {1065impl PropertyScope {
1066 /// Apply scope to property key.
782 pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {1067 pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {
783 let scope_str: &[u8] = match self {1068 let scope_str: &[u8] = match self {
784 Self::None => return Ok(key),1069 Self::None => return Ok(key),
792 }1077 }
793}1078}
7941079
1080/// Trait for operate with properties.
795pub trait TrySetProperty: Sized {1081pub trait TrySetProperty: Sized {
796 type Value;1082 type Value;
7971083
1084 /// Try to set property with scope.
798 fn try_scoped_set(1085 fn try_scoped_set(
799 &mut self,1086 &mut self,
800 scope: PropertyScope,1087 scope: PropertyScope,
801 key: PropertyKey,1088 key: PropertyKey,
802 value: Self::Value,1089 value: Self::Value,
803 ) -> Result<(), PropertiesError>;1090 ) -> Result<(), PropertiesError>;
8041091
1092 /// Try to set property with scope from iterator.
805 fn try_scoped_set_from_iter<I, KV>(1093 fn try_scoped_set_from_iter<I, KV>(
806 &mut self,1094 &mut self,
807 scope: PropertyScope,1095 scope: PropertyScope,
819 Ok(())1107 Ok(())
820 }1108 }
8211109
1110 /// Try to set property.
822 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {1111 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {
823 self.try_scoped_set(PropertyScope::None, key, value)1112 self.try_scoped_set(PropertyScope::None, key, value)
824 }1113 }
8251114
1115 /// Try to set property from iterator.
826 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>1116 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>
827 where1117 where
828 I: Iterator<Item = KV>,1118 I: Iterator<Item = KV>,
832 }1122 }
833}1123}
8341124
1125/// Wrapped map for storing properties.
835#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]1126#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]
836#[derivative(Default(bound = ""))]1127#[derivative(Default(bound = ""))]
837pub struct PropertiesMap<Value>(1128pub struct PropertiesMap<Value>(
838 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,1129 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,
839);1130);
8401131
841impl<Value> PropertiesMap<Value> {1132impl<Value> PropertiesMap<Value> {
1133 /// Create new property map.
842 pub fn new() -> Self {1134 pub fn new() -> Self {
843 Self(BoundedBTreeMap::new())1135 Self(BoundedBTreeMap::new())
844 }1136 }
8451137
1138 /// Remove property from map.
846 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {1139 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {
847 Self::check_property_key(key)?;1140 Self::check_property_key(key)?;
8481141
849 Ok(self.0.remove(key))1142 Ok(self.0.remove(key))
850 }1143 }
8511144
1145 /// Get property with appropriate key from map.
852 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {1146 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {
853 self.0.get(key)1147 self.0.get(key)
854 }1148 }
8551149
1150 /// Check if map contains key.
856 pub fn contains_key(&self, key: &PropertyKey) -> bool {1151 pub fn contains_key(&self, key: &PropertyKey) -> bool {
857 self.0.contains_key(key)1152 self.0.contains_key(key)
858 }1153 }
8591154
1155 /// Check if map contains key with key validation.
860 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {1156 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {
861 if key.is_empty() {1157 if key.is_empty() {
862 return Err(PropertiesError::EmptyPropertyKey);1158 return Err(PropertiesError::EmptyPropertyKey);
909 }1205 }
910}1206}
9111207
1208/// Alias for property permissions map.
912pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;1209pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;
9131210
1211/// Wrapper for properties map with consumed space control.
914#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]1212#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]
915pub struct Properties {1213pub struct Properties {
916 map: PropertiesMap<PropertyValue>,1214 map: PropertiesMap<PropertyValue>,
919}1217}
9201218
921impl Properties {1219impl Properties {
1220 /// Create new properies container.
922 pub fn new(space_limit: u32) -> Self {1221 pub fn new(space_limit: u32) -> Self {
923 Self {1222 Self {
924 map: PropertiesMap::new(),1223 map: PropertiesMap::new(),
927 }1226 }
928 }1227 }
9291228
1229 /// Remove propery with appropiate key.
930 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {1230 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {
931 let value = self.map.remove(key)?;1231 let value = self.map.remove(key)?;
9321232
938 Ok(value)1238 Ok(value)
939 }1239 }
9401240
1241 /// Get property with appropriate key.
941 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {1242 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {
942 self.map.get(key)1243 self.map.get(key)
943 }1244 }
977 }1278 }
978}1279}
9791280
1281/// Utility struct for using in `StorageMap`.
980pub struct CollectionProperties;1282pub struct CollectionProperties;
9811283
982impl Get<Properties> for CollectionProperties {1284impl Get<Properties> for CollectionProperties {
985 }1287 }
986}1288}
9871289
1290/// Utility struct for using in `StorageMap`.
988pub struct TokenProperties;1291pub struct TokenProperties;
9891292
990impl Get<Properties> for TokenProperties {1293impl Get<Properties> for TokenProperties {
modifiedprimitives/data-structs/src/mapping.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/mapping.rs
+++ b/primitives/data-structs/src/mapping.rs
@@ -1,3 +1,21 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+//! This module contains mapping between different addresses.
+
 use core::marker::PhantomData;
 
 use sp_core::H160;
@@ -5,12 +23,19 @@
 use crate::{CollectionId, TokenId};
 use pallet_evm::account::CrossAccountId;
 
+/// Trait for mapping between token id and some `Address`.
 pub trait TokenAddressMapping<Address> {
+	/// Map token id to `Address`.
 	fn token_to_address(collection: CollectionId, token: TokenId) -> Address;
+
+	/// Map `Address` to token id.
 	fn address_to_token(address: &Address) -> Option<(CollectionId, TokenId)>;
+
+	/// Check is address for token.
 	fn is_token_address(address: &Address) -> bool;
 }
 
+/// Unit struct for mapping token id to/from *Evm address* represented by [`H160`].
 pub struct EvmTokenAddressMapping;
 
 /// 0xf8238ccfff8ed887463fd5e00000000100000002  - collection 1, token 2
@@ -46,6 +71,7 @@
 	}
 }
 
+/// Unit struct for mapping token id to/from [`CrossAccountId`].
 pub struct CrossTokenAddressMapping<A>(PhantomData<A>);
 
 impl<A, C: CrossAccountId<A>> TokenAddressMapping<C> for CrossTokenAddressMapping<A> {
modifiedprimitives/rpc/src/lib.rsdiffbeforeafterboth
--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -28,6 +28,7 @@
 
 sp_api::decl_runtime_apis! {
 	#[api_version(2)]
+	/// Trait for generate rpc.
 	pub trait UniqueApi<CrossAccountId, AccountId> where
 		AccountId: Decode,
 		CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,
@@ -35,36 +36,57 @@
 		#[changed_in(2)]
 		fn token_owner(collection: CollectionId, token: TokenId) -> Result<CrossAccountId>;
 
+		/// Get number of tokens in collection owned by account.
 		fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>>;
+
+		/// Number of existing tokens in collection.
 		fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>>;
+
+		/// Check token exist.
 		fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool>;
 
+		/// Get token owner.
 		fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
+
+		/// Get real owner of nested token.
 		fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
+
+		/// Get nested tokens for the specified item.
 		fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>>;
 
+		/// Get collection properties.
 		fn collection_properties(collection: CollectionId, properties: Option<Vec<Vec<u8>>>) -> Result<Vec<Property>>;
 
+		/// Get token properties.
 		fn token_properties(
 			collection: CollectionId,
 			token_id: TokenId,
 			properties: Option<Vec<Vec<u8>>>
 		) -> Result<Vec<Property>>;
 
+		/// Get permissions for token properties.
 		fn property_permissions(
 			collection: CollectionId,
 			properties: Option<Vec<Vec<u8>>>
 		) -> Result<Vec<PropertyKeyPermission>>;
 
+		/// Get token data.
 		fn token_data(
 			collection: CollectionId,
 			token_id: TokenId,
 			keys: Option<Vec<Vec<u8>>>
 		) -> Result<TokenData<CrossAccountId>>;
 
+		/// Total number of tokens in collection.
 		fn total_supply(collection: CollectionId) -> Result<u32>;
+
+		/// Get account balance for collection (sum of tokens pieces).
 		fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32>;
+
+		/// Get account balance for specified token.
 		fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128>;
+
+		/// Amount of token pieces allowed to spend from granded account.
 		fn allowance(
 			collection: CollectionId,
 			sender: CrossAccountId,
@@ -72,14 +94,31 @@
 			token: TokenId,
 		) -> Result<u128>;
 
+		/// Get list of collection admins.
 		fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>>;
+
+		/// Get list of users that allowet to mint tikens in collection.
 		fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>>;
+
+		/// Check that user is in allowed list (see [`allowlist`]).
 		fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool>;
+
+		/// Last minted token id.
 		fn last_token_id(collection: CollectionId) -> Result<TokenId>;
+
+		/// Get collection by id.
 		fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>>;
+
+		/// Get collection stats.
 		fn collection_stats() -> Result<CollectionStats>;
+
+		/// Get the number of blocks through which sponsorship will be available.
 		fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>>;
+
+		/// Get effective colletion limits.
 		fn effective_collection_limits(collection_id: CollectionId) -> Result<Option<CollectionLimits>>;
+
+		/// Get total pieces of token.
 		fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Result<Option<u128>>;
 		fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec<CrossAccountId>>;
 	}