git.delta.rocks / unique-network / refs/commits / 06c6a41ee252

difftreelog

doc

Trubnikov Sergey2022-07-28parent: #26c4de6.patch.diff
in: master

4 files changed

modifiedprimitives/data-structs/src/bounded.rsdiffbeforeafterboth
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
2// This file is part of Unique Network.
3
4// Unique Network is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Unique Network is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// 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/>.
16
17//! This module contins implementations for support bounded structures in [`serde`].
18
1use core::fmt;19use core::fmt;
2use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet};20use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet};
7 storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},25 storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},
8};26};
927
10/// BoundedVec doesn't supports serde28/// [`serde`] implementations for [`BoundedVec`].
11#[cfg(feature = "serde1")]29#[cfg(feature = "serde1")]
12pub mod vec_serde {30pub mod vec_serde {
13 use core::convert::TryFrom;31 use core::convert::TryFrom;
39 }57 }
40}58}
4159
60/// Format [`BoundedVec`] for debug output.
42pub fn vec_debug<V, S>(v: &BoundedVec<V, S>, f: &mut fmt::Formatter) -> Result<(), fmt::Error>61pub fn vec_debug<V, S>(v: &BoundedVec<V, S>, f: &mut fmt::Formatter) -> Result<(), fmt::Error>
43where62where
44 V: fmt::Debug,63 V: fmt::Debug,
4968
50#[cfg(feature = "serde1")]69#[cfg(feature = "serde1")]
51#[allow(dead_code)]70#[allow(dead_code)]
71/// [`serde`] implementations for [`BoundedBTreeMap`].
52pub mod map_serde {72pub mod map_serde {
53 use core::convert::TryFrom;73 use core::convert::TryFrom;
54 use sp_std::collections::btree_map::BTreeMap;74 use sp_std::collections::btree_map::BTreeMap;
84 }104 }
85}105}
86106
107/// Format [`BoundedBTreeMap`] for debug output.
87pub fn map_debug<K, V, S>(108pub fn map_debug<K, V, S>(
88 v: &BoundedBTreeMap<K, V, S>,109 v: &BoundedBTreeMap<K, V, S>,
89 f: &mut fmt::Formatter,110 f: &mut fmt::Formatter,
98119
99#[cfg(feature = "serde1")]120#[cfg(feature = "serde1")]
100#[allow(dead_code)]121#[allow(dead_code)]
122/// [`serde`] implementations for [`BoundedBTreeSet`].
101pub mod set_serde {123pub mod set_serde {
102 use core::convert::TryFrom;124 use core::convert::TryFrom;
103 use sp_std::collections::btree_set::BTreeSet;125 use sp_std::collections::btree_set::BTreeSet;
129 }151 }
130}152}
131153
154/// Format [`BoundedBTreeSet`] for debug output.
132pub fn set_debug<K, S>(v: &BoundedBTreeSet<K, S>, f: &mut fmt::Formatter) -> Result<(), fmt::Error>155pub fn set_debug<K, S>(v: &BoundedBTreeSet<K, S>, f: &mut fmt::Formatter) -> Result<(), fmt::Error>
133where156where
134 K: fmt::Debug + Ord,157 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 amount of types, traits and constants.
1620
17#![cfg_attr(not(feature = "std"), no_std)]21#![cfg_attr(not(feature = "std"), no_std)]
1822
83 1087 10
84};88};
89
90/// Maximum admins per collection.
85pub const COLLECTION_ADMINS_LIMIT: u32 = 5;91pub const COLLECTION_ADMINS_LIMIT: u32 = 5;
92
93/// Maximum tokens per collection.
86pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;94pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;
95
96/// Maximum tokens per account.
87pub 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")) {
88 1_000_00098 1_000_000
89} else {99} else {
90 10100 10
91};101};
92102
93// Timeouts for item types in passed blocks103/// Default timeout for transfer sponsoring NFT item.
94pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;104pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;
105/// Default timeout for transfer sponsoring fungible item.
95pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;106pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;
107/// Default timeout for transfer sponsoring refungible item.
96pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;108pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;
97109
110/// Default timeout for sponsored approving.
98pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;111pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;
99112
100// Schema limits113// Schema limits
101pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;114pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;
102pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;115pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;
103pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;116pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;
104117
118// TODO: not used. Delete?
105pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;119pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;
106120
121/// Maximum length for collection name.
107pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;122pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;
123
124/// Maximum length for collection description.
108pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;125pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;
126
127/// Maximal token prefix length.
109pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;128pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;
110129
130/// Maximal lenght of property key.
111pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;131pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;
132
133/// Maximal lenght of property value.
112pub 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.
113pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;137pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;
114138
139/// Maximal lenght of extended property value.
115pub const MAX_AUX_PROPERTY_VALUE_LENGTH: u32 = 2048;140pub const MAX_AUX_PROPERTY_VALUE_LENGTH: u32 = 2048;
116141
142/// Maximum size for all collection properties.
117pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;143pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;
144
145/// Maximum size for all token properties.
118pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;146pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;
119147
120/// How much items can be created per single148/// How much items can be created per single
121/// create_many call149/// create_many call.
122pub const MAX_ITEMS_PER_BATCH: u32 = 200;150pub const MAX_ITEMS_PER_BATCH: u32 = 200;
123151
124/// Used for limit bounded types of token custom data.152/// Used for limit bounded types of token custom data.
144impl EncodeLike<u32> for CollectionId {}172impl EncodeLike<u32> for CollectionId {}
145impl EncodeLike<CollectionId> for u32 {}173impl EncodeLike<CollectionId> for u32 {}
146174
147/// Token id175/// Token id.
148#[derive(176#[derive(
149 Encode,177 Encode,
150 Decode,178 Decode,
190 }218 }
191}219}
192220
221/// Token data.
193#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]222#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
194#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]223#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
195pub struct TokenData<CrossAccountId> {224pub struct TokenData<CrossAccountId> {
225 /// Properties of token.
196 pub properties: Vec<Property>,226 pub properties: Vec<Property>,
227
228 /// Token owner.
197 pub owner: Option<CrossAccountId>,229 pub owner: Option<CrossAccountId>,
230
231 /// Token pieces.
198 pub pieces: u128,232 pub pieces: u128,
199}233}
200234
241 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;275 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;
242}276}
243277
244/// Access mode for token.278/// Access mode for some token operations.
245#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]279#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]
246#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]280#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
247pub enum AccessMode {281pub enum AccessMode {
474/// 508///
475/// Update with `pallet_common::Pallet::clamp_limits`.509/// Update with `pallet_common::Pallet::clamp_limits`.
476// 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
477// TODO: move `pallet_common::Pallet::clamp_limits() in pallet-common.` into `impl CollectionLimits`.
478#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]511#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
479#[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.
480pub struct CollectionLimits {516pub struct CollectionLimits {
481 /// How many tokens can a user have on one account.517 /// How many tokens can a user have on one account.
482 /// * Default - [`ACCOUNT_TOKEN_OWNERSHIP_LIMIT`].518 /// * Default - [`ACCOUNT_TOKEN_OWNERSHIP_LIMIT`].
483 /// * Limit - [`MAX_TOKEN_OWNERSHIP`].519 /// * Limit - [`MAX_TOKEN_OWNERSHIP`].
484 pub account_token_ownership_limit: Option<u32>,520 pub account_token_ownership_limit: Option<u32>,
485521
486 /// Maximum size of data in bytes of a sponsored transaction.522 /// How many bytes of data are available for sponsorship.
487 /// * Default - [`CUSTOM_DATA_LIMIT`].523 /// * Default - [`CUSTOM_DATA_LIMIT`].
524 /// * Limit - [`CUSTOM_DATA_LIMIT`].
488 pub sponsored_data_size: Option<u32>,525 pub sponsored_data_size: Option<u32>,
489526
490 /// FIXME should we delete this or repurpose it?527 // FIXME should we delete this or repurpose it?
491 /// None - setVariableMetadata is not sponsored528 /// Times in how many blocks we sponsor data.
492 /// Some(v) - setVariableMetadata is sponsored529 ///
493 /// 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`].
494 ///534 ///
495 /// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]535 /// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]
496 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,536 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,
497 /// 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`].
498 pub token_limit: Option<u32>,543 pub token_limit: Option<u32>,
499544
500 /// Timeout for sponsoring a token transfer in passed blocks. Chain default:545 /// Timeouts for transfer sponsoring.
501 /// either [`NFT_SPONSOR_TRANSFER_TIMEOUT`], [`FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`], or [`REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`],546 ///
502 /// 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`].
503 pub sponsor_transfer_timeout: Option<u32>,552 pub sponsor_transfer_timeout: Option<u32>,
553
504 /// 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`].
505 pub sponsor_approve_timeout: Option<u32>,558 pub sponsor_approve_timeout: Option<u32>,
506 /// 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**.
507 pub owner_can_transfer: Option<bool>,563 pub owner_can_transfer: Option<bool>,
508 /// 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**.
509 pub owner_can_destroy: Option<bool>,568 pub owner_can_destroy: Option<bool>,
510 /// 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**.
511 pub transfers_enabled: Option<bool>,573 pub transfers_enabled: Option<bool>,
512}574}
513575
514impl CollectionLimits {576impl CollectionLimits {
577 /// Get effective value for [`account_token_ownership_limit`](self.account_token_ownership_limit).
515 pub fn account_token_ownership_limit(&self) -> u32 {578 pub fn account_token_ownership_limit(&self) -> u32 {
516 self.account_token_ownership_limit579 self.account_token_ownership_limit
517 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)580 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)
518 .min(MAX_TOKEN_OWNERSHIP)581 .min(MAX_TOKEN_OWNERSHIP)
519 }582 }
583
584 /// Get effective value for [`sponsored_data_size`](self.sponsored_data_size).
520 pub fn sponsored_data_size(&self) -> u32 {585 pub fn sponsored_data_size(&self) -> u32 {
521 self.sponsored_data_size586 self.sponsored_data_size
522 .unwrap_or(CUSTOM_DATA_LIMIT)587 .unwrap_or(CUSTOM_DATA_LIMIT)
523 .min(CUSTOM_DATA_LIMIT)588 .min(CUSTOM_DATA_LIMIT)
524 }589 }
590
591 /// Get effective value for [`token_limit`](self.token_limit).
525 pub fn token_limit(&self) -> u32 {592 pub fn token_limit(&self) -> u32 {
526 self.token_limit593 self.token_limit
527 .unwrap_or(COLLECTION_TOKEN_LIMIT)594 .unwrap_or(COLLECTION_TOKEN_LIMIT)
528 .min(COLLECTION_TOKEN_LIMIT)595 .min(COLLECTION_TOKEN_LIMIT)
529 }596 }
597
598 // TODO: may be replace u32 to mode?
599 /// Get effective value for [`sponsor_transfer_timeout`](self.sponsor_transfer_timeout).
530 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {600 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {
531 self.sponsor_transfer_timeout601 self.sponsor_transfer_timeout
532 .unwrap_or(default)602 .unwrap_or(default)
533 .min(MAX_SPONSOR_TIMEOUT)603 .min(MAX_SPONSOR_TIMEOUT)
534 }604 }
605
606 /// Get effective value for [`sponsor_approve_timeout`](self.sponsor_approve_timeout).
535 pub fn sponsor_approve_timeout(&self) -> u32 {607 pub fn sponsor_approve_timeout(&self) -> u32 {
536 self.sponsor_approve_timeout608 self.sponsor_approve_timeout
537 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)609 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)
538 .min(MAX_SPONSOR_TIMEOUT)610 .min(MAX_SPONSOR_TIMEOUT)
539 }611 }
612
613 /// Get effective value for [`owner_can_transfer`](self.owner_can_transfer).
540 pub fn owner_can_transfer(&self) -> bool {614 pub fn owner_can_transfer(&self) -> bool {
541 self.owner_can_transfer.unwrap_or(false)615 self.owner_can_transfer.unwrap_or(false)
542 }616 }
617
618 /// Get effective value for [`owner_can_transfer_instaled`](self.owner_can_transfer_instaled).
543 pub fn owner_can_transfer_instaled(&self) -> bool {619 pub fn owner_can_transfer_instaled(&self) -> bool {
544 self.owner_can_transfer.is_some()620 self.owner_can_transfer.is_some()
545 }621 }
622
623 /// Get effective value for [`owner_can_destroy`](self.owner_can_destroy).
546 pub fn owner_can_destroy(&self) -> bool {624 pub fn owner_can_destroy(&self) -> bool {
547 self.owner_can_destroy.unwrap_or(true)625 self.owner_can_destroy.unwrap_or(true)
548 }626 }
627
628 /// Get effective value for [`transfers_enabled`](self.transfers_enabled).
549 pub fn transfers_enabled(&self) -> bool {629 pub fn transfers_enabled(&self) -> bool {
550 self.transfers_enabled.unwrap_or(true)630 self.transfers_enabled.unwrap_or(true)
551 }631 }
632
633 /// Get effective value for [`sponsored_data_rate_limit`](self.sponsored_data_rate_limit).
552 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {634 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {
553 match self635 match self
554 .sponsored_data_rate_limit636 .sponsored_data_rate_limit
561}643}
562644
563/// Permissions on certain operations within a collection.645/// Permissions on certain operations within a collection.
646///
564/// All fields are wrapped in `Option`s, where None means chain default.647/// Some fields are wrapped in [`Option`], where `None` means chain default.
565// IMPORTANT: When adding/removing fields from this struct - don't forget to also648///
566// update clamp_limits() in pallet-common.649/// Update with `pallet_common::Pallet::clamp_permissions`.
567#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]650#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
568#[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`.
569pub struct CollectionPermissions {654pub struct CollectionPermissions {
655 /// Access mode.
656 ///
657 /// * Default - [`AccessMode::Normal`].
570 pub access: Option<AccessMode>,658 pub access: Option<AccessMode>,
659
660 /// Minting allowance.
661 ///
662 /// * Default - **false**.
571 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**
572 pub nesting: Option<NestingPermissions>,671 pub nesting: Option<NestingPermissions>,
573}672}
574673
575impl CollectionPermissions {674impl CollectionPermissions {
675 /// Get effective value for [`access`](self.access).
576 pub fn access(&self) -> AccessMode {676 pub fn access(&self) -> AccessMode {
577 self.access.unwrap_or(AccessMode::Normal)677 self.access.unwrap_or(AccessMode::Normal)
578 }678 }
679
680 /// Get effective value for [`mint_mode`](self.mint_mode).
579 pub fn mint_mode(&self) -> bool {681 pub fn mint_mode(&self) -> bool {
580 self.mint_mode.unwrap_or(false)682 self.mint_mode.unwrap_or(false)
581 }683 }
684
685 /// Get effective value for [`nesting`](self.nesting).
582 pub fn nesting(&self) -> &NestingPermissions {686 pub fn nesting(&self) -> &NestingPermissions {
583 static DEFAULT: NestingPermissions = NestingPermissions {687 static DEFAULT: NestingPermissions = NestingPermissions {
584 token_owner: false,688 token_owner: false,
591 }695 }
592}696}
593697
698/// Inner set for collections allowed to nest.
594type OwnerRestrictedSetInner = BoundedBTreeSet<CollectionId, ConstU32<16>>;699type OwnerRestrictedSetInner = BoundedBTreeSet<CollectionId, ConstU32<16>>;
595700
701/// Wraper for collections set allowing nest.
596#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]702#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]
597#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]703#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
598#[derivative(Debug)]704#[derivative(Debug)]
603);709);
710
604impl OwnerRestrictedSet {711impl OwnerRestrictedSet {
712 /// Create new set.
605 pub fn new() -> Self {713 pub fn new() -> Self {
606 Self(Default::default())714 Self(Default::default())
607 }715 }
623#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]731#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
624#[derivative(Debug)]732#[derivative(Debug)]
625pub struct NestingPermissions {733pub struct NestingPermissions {
626 /// Owner of token can nest tokens under it734 /// Owner of token can nest tokens under it.
627 pub token_owner: bool,735 pub token_owner: bool,
628 /// Admin of token collection can nest tokens under token736 /// Admin of token collection can nest tokens under token.
629 pub collection_admin: bool,737 pub collection_admin: bool,
630 /// If set - only tokens from specified collections can be nested738 /// If set - only tokens from specified collections can be nested.
631 pub restricted: Option<OwnerRestrictedSet>,739 pub restricted: Option<OwnerRestrictedSet>,
632740
633 #[cfg(feature = "runtime-benchmarks")]741 #[cfg(feature = "runtime-benchmarks")]
634 /// Anyone can nest tokens, mutually exclusive with `token_owner`, `admin`742 /// Anyone can nest tokens, mutually exclusive with `token_owner`, `admin`.
635 pub permissive: bool,743 pub permissive: bool,
636}744}
637745
638/// 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).
639#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]749#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]
640#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]750#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
641pub enum SponsoringRateLimit {751pub enum SponsoringRateLimit {
653 /// Key-value pairs used to describe the token as metadata763 /// Key-value pairs used to describe the token as metadata
654 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]764 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
655 #[derivative(Debug(format_with = "bounded::vec_debug"))]765 #[derivative(Debug(format_with = "bounded::vec_debug"))]
766 /// Properties that wil be assignet to created item.
656 pub properties: CollectionPropertiesVec,767 pub properties: CollectionPropertiesVec,
657}768}
658769
674 #[derivative(Debug(format_with = "bounded::vec_debug"))]785 #[derivative(Debug(format_with = "bounded::vec_debug"))]
675 pub const_data: BoundedVec<u8, CustomDataLimit>,786 pub const_data: BoundedVec<u8, CustomDataLimit>,
676787
677 /// Number of pieces the RFT is split into788 /// Pieces of created token.
678 pub pieces: u128,789 pub pieces: u128,
679790
680 /// Key-value pairs used to describe the token as metadata791 /// Key-value pairs used to describe the token as metadata
683 pub properties: CollectionPropertiesVec,794 pub properties: CollectionPropertiesVec,
684}795}
685796
797// TODO: remove this.
686#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]798#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
687#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]799#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
688pub enum MetaUpdatePermission {800pub enum MetaUpdatePermission {
692}804}
693805
694/// 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.
695#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]808#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
696#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]809#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
697pub enum CreateItemData {810pub enum CreateItemData {
811 /// Data for create NFT.
698 NFT(CreateNftData),812 NFT(CreateNftData),
813 /// Data for create Fungible item.
699 Fungible(CreateFungibleData),814 Fungible(CreateFungibleData),
815 /// Data for create ReFungible item.
700 ReFungible(CreateReFungibleData),816 ReFungible(CreateReFungibleData),
701}817}
702818
703/// Explicit NFT creation data with meta parameters.819/// Extended data for create NFT.
704#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]820#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]
705#[derivative(Debug)]821#[derivative(Debug)]
706pub struct CreateNftExData<CrossAccountId> {822pub struct CreateNftExData<CrossAccountId> {
823 /// Properties that wil be assignet to created item.
707 #[derivative(Debug(format_with = "bounded::vec_debug"))]824 #[derivative(Debug(format_with = "bounded::vec_debug"))]
708 pub properties: CollectionPropertiesVec,825 pub properties: CollectionPropertiesVec,
826
827 /// Owner of creating item.
709 pub owner: CrossAccountId,828 pub owner: CrossAccountId,
710}829}
711830
712/// Explicit RFT creation data with meta parameters.831/// Extended data for create ReFungible item.
713#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]832#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]
714#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]833#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]
715pub struct CreateRefungibleExData<CrossAccountId> {834pub struct CreateRefungibleExData<CrossAccountId> {
835 /// Custom data stored in token.
716 #[derivative(Debug(format_with = "bounded::vec_debug"))]836 #[derivative(Debug(format_with = "bounded::vec_debug"))]
717 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.
718 #[derivative(Debug(format_with = "bounded::map_debug"))]840 #[derivative(Debug(format_with = "bounded::map_debug"))]
719 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,841 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,
720 #[derivative(Debug(format_with = "bounded::vec_debug"))]842 #[derivative(Debug(format_with = "bounded::vec_debug"))]
721 pub properties: CollectionPropertiesVec,843 pub properties: CollectionPropertiesVec,
722}844}
723845
724/// Explicit item creation data with meta parameters, namely the owner.846/// Unified extended data for creating item.
725#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]847#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]
726#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]848#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]
727pub enum CreateItemExData<CrossAccountId> {849pub enum CreateItemExData<CrossAccountId> {
850 /// Extended data for create NFT.
728 NFT(851 NFT(
729 #[derivative(Debug(format_with = "bounded::vec_debug"))]852 #[derivative(Debug(format_with = "bounded::vec_debug"))]
730 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,853 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,
731 ),854 ),
855
856 /// Extended data for create Fungible item.
732 Fungible(857 Fungible(
733 #[derivative(Debug(format_with = "bounded::map_debug"))]858 #[derivative(Debug(format_with = "bounded::map_debug"))]
734 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,859 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,
735 ),860 ),
861
862 /// Extended data for create ReFungible item in case of
736 /// Many tokens, each may have only one owner863 /// many tokens, each may have only one owner
737 RefungibleMultipleItems(864 RefungibleMultipleItems(
738 #[derivative(Debug(format_with = "bounded::vec_debug"))]865 #[derivative(Debug(format_with = "bounded::vec_debug"))]
739 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,866 BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,
740 ),867 ),
868
869 /// Extended data for create ReFungible item in case of
741 /// Single token, which may have many owners870 /// single token, which may have many owners
742 RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),871 RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),
743}872}
744873
745impl CreateItemData {874impl CreateItemData {
875 /// Get size of custom data.
746 pub fn data_size(&self) -> usize {876 pub fn data_size(&self) -> usize {
747 match self {877 match self {
748 CreateItemData::ReFungible(data) => data.const_data.len(),878 CreateItemData::ReFungible(data) => data.const_data.len(),
774#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]904#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
775// todo possibly rename to be used generally as an address pair905// todo possibly rename to be used generally as an address pair
776pub struct TokenChild {906pub struct TokenChild {
907 /// Token id.
777 pub token: TokenId,908 pub token: TokenId,
909
910 /// Collection id.
778 pub collection: CollectionId,911 pub collection: CollectionId,
779}912}
780913
914/// Collection statistics.
781#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]915#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]
782#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]916#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
783pub struct CollectionStats {917pub struct CollectionStats {
918 /// Number of created items.
784 pub created: u32,919 pub created: u32,
920
921 /// Number of burned items.
785 pub destroyed: u32,922 pub destroyed: u32,
923
924 /// Number of current items.
786 pub alive: u32,925 pub alive: u32,
787}926}
788927
928/// This type works like [`PhantomData`] but supports generating _scale-info_ descriptions to generate node metadata.
789#[derive(Encode, Decode, Clone, Debug)]929#[derive(Encode, Decode, Clone, Debug)]
790#[cfg_attr(feature = "std", derive(PartialEq))]930#[cfg_attr(feature = "std", derive(PartialEq))]
791pub struct PhantomType<T>(core::marker::PhantomData<T>);931pub struct PhantomType<T>(core::marker::PhantomData<T>);
811 }951 }
812}952}
813953
954/// Bounded vector of bytes.
814pub type BoundedBytes<S> = BoundedVec<u8, S>;955pub type BoundedBytes<S> = BoundedVec<u8, S>;
815956
957/// Extra properties for external collections.
816pub type AuxPropertyValue = BoundedBytes<ConstU32<MAX_AUX_PROPERTY_VALUE_LENGTH>>;958pub type AuxPropertyValue = BoundedBytes<ConstU32<MAX_AUX_PROPERTY_VALUE_LENGTH>>;
817959
960/// Property key.
818pub type PropertyKey = BoundedBytes<ConstU32<MAX_PROPERTY_KEY_LENGTH>>;961pub type PropertyKey = BoundedBytes<ConstU32<MAX_PROPERTY_KEY_LENGTH>>;
962
963/// Property value.
819pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;964pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;
820965
966/// Property permission.
821#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]967#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]
822#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]968#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
823pub 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**.
824 pub mutable: bool,973 pub mutable: bool,
974
975 /// Change permission for the collection administrator.
825 pub collection_admin: bool,976 pub collection_admin: bool,
977
978 /// Permission to change the property for the owner of the token.
826 pub token_owner: bool,979 pub token_owner: bool,
827}980}
828981
829impl PropertyPermission {982impl PropertyPermission {
983 /// Creates mutable property permission but changes restricted for collection admin and token owner.
830 pub fn none() -> Self {984 pub fn none() -> Self {
831 Self {985 Self {
832 mutable: true,986 mutable: true,
836 }990 }
837}991}
838992
993/// Property is simpl key-value record.
839#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]994#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]
840#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]995#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
841pub struct Property {996pub struct Property {
997 /// Property key.
842 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]998 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
843 pub key: PropertyKey,999 pub key: PropertyKey,
8441000
1001 /// Property value.
845 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1002 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
846 pub value: PropertyValue,1003 pub value: PropertyValue,
847}1004}
852 }1009 }
853}1010}
8541011
1012/// Record for proprty key permission.
855#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]1013#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]
856#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1014#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
857pub struct PropertyKeyPermission {1015pub struct PropertyKeyPermission {
1016 /// Key.
858 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1017 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
859 pub key: PropertyKey,1018 pub key: PropertyKey,
8601019
1020 /// Permission.
861 pub permission: PropertyPermission,1021 pub permission: PropertyPermission,
862}1022}
8631023
867 }1027 }
868}1028}
8691029
1030/// Errors for properties actions.
870#[derive(Debug)]1031#[derive(Debug)]
871pub 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`].
872 NoSpaceForProperty,1037 NoSpaceForProperty,
1038
1039 /// The property limit has been reached.
1040 ///
1041 /// * Limit - [`MAX_PROPERTIES_PER_ITEM`].
873 PropertyLimitReached,1042 PropertyLimitReached,
1043
1044 /// Property key contains not allowed character.
874 InvalidCharacterInPropertyKey,1045 InvalidCharacterInPropertyKey,
1046
1047 /// Property key length is too long.
1048 ///
1049 /// * Limit - [`MAX_PROPERTY_KEY_LENGTH`].
875 PropertyKeyIsTooLong,1050 PropertyKeyIsTooLong,
1051
1052 /// Property key is empty.
876 EmptyPropertyKey,1053 EmptyPropertyKey,
877}1054}
8781055
1056/// Marker for scope of property.
1057///
1058/// Scoped property can't be changed by user. Used for external collections.
879#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Clone, Copy)]1059#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Clone, Copy)]
880pub enum PropertyScope {1060pub enum PropertyScope {
881 None,1061 None,
882 Rmrk,1062 Rmrk,
883}1063}
8841064
885impl PropertyScope {1065impl PropertyScope {
1066 /// Apply scope to property key.
886 pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {1067 pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {
887 let scope_str: &[u8] = match self {1068 let scope_str: &[u8] = match self {
888 Self::None => return Ok(key),1069 Self::None => return Ok(key),
896 }1077 }
897}1078}
8981079
1080/// Trait for operate with properties.
899pub trait TrySetProperty: Sized {1081pub trait TrySetProperty: Sized {
900 type Value;1082 type Value;
9011083
1084 /// Try to set property with scope.
902 fn try_scoped_set(1085 fn try_scoped_set(
903 &mut self,1086 &mut self,
904 scope: PropertyScope,1087 scope: PropertyScope,
907 ) -> Result<(), PropertiesError>;1090 ) -> Result<(), PropertiesError>;
9081091
1092
1093 /// Try to set property with scope from iterator.
909 fn try_scoped_set_from_iter<I, KV>(1094 fn try_scoped_set_from_iter<I, KV>(
910 &mut self,1095 &mut self,
911 scope: PropertyScope,1096 scope: PropertyScope,
923 Ok(())1108 Ok(())
924 }1109 }
9251110
1111 /// Try to set property.
926 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {1112 fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {
927 self.try_scoped_set(PropertyScope::None, key, value)1113 self.try_scoped_set(PropertyScope::None, key, value)
928 }1114 }
9291115
1116 /// Try to set property from iterator.
930 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>1117 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>
931 where1118 where
932 I: Iterator<Item = KV>,1119 I: Iterator<Item = KV>,
936 }1123 }
937}1124}
9381125
1126/// Wrapped map for storing properties.
939#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]1127#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]
940#[derivative(Default(bound = ""))]1128#[derivative(Default(bound = ""))]
941pub struct PropertiesMap<Value>(1129pub struct PropertiesMap<Value>(
942 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,1130 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,
943);1131);
9441132
945impl<Value> PropertiesMap<Value> {1133impl<Value> PropertiesMap<Value> {
1134 /// Create new property map.
946 pub fn new() -> Self {1135 pub fn new() -> Self {
947 Self(BoundedBTreeMap::new())1136 Self(BoundedBTreeMap::new())
948 }1137 }
9491138
1139 /// Remove property from map.
950 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {1140 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {
951 Self::check_property_key(key)?;1141 Self::check_property_key(key)?;
9521142
953 Ok(self.0.remove(key))1143 Ok(self.0.remove(key))
954 }1144 }
9551145
1146 /// Get property with appropriate key from map.
956 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {1147 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {
957 self.0.get(key)1148 self.0.get(key)
958 }1149 }
9591150
1151 /// Check if map contains key.
960 pub fn contains_key(&self, key: &PropertyKey) -> bool {1152 pub fn contains_key(&self, key: &PropertyKey) -> bool {
961 self.0.contains_key(key)1153 self.0.contains_key(key)
962 }1154 }
9631155
1156 /// Check if map contains key with key validation.
964 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {1157 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {
965 if key.is_empty() {1158 if key.is_empty() {
966 return Err(PropertiesError::EmptyPropertyKey);1159 return Err(PropertiesError::EmptyPropertyKey);
1013 }1206 }
1014}1207}
10151208
1209/// Alias for property permissions map.
1016pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;1210pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;
10171211
1212/// Wrapper for properties map with consumed space control.
1018#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]1213#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]
1019pub struct Properties {1214pub struct Properties {
1020 map: PropertiesMap<PropertyValue>,1215 map: PropertiesMap<PropertyValue>,
1023}1218}
10241219
1025impl Properties {1220impl Properties {
1221 /// Create new properies container.
1026 pub fn new(space_limit: u32) -> Self {1222 pub fn new(space_limit: u32) -> Self {
1027 Self {1223 Self {
1028 map: PropertiesMap::new(),1224 map: PropertiesMap::new(),
1031 }1227 }
1032 }1228 }
10331229
1230 /// Remove propery with appropiate key.
1034 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {1231 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {
1035 let value = self.map.remove(key)?;1232 let value = self.map.remove(key)?;
10361233
1042 Ok(value)1239 Ok(value)
1043 }1240 }
10441241
1242 /// Get property with appropriate key.
1045 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {1243 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {
1046 self.map.get(key)1244 self.map.get(key)
1047 }1245 }
1081 }1279 }
1082}1280}
10831281
1282/// Utility struct for using in `StorageMap`.
1084pub struct CollectionProperties;1283pub struct CollectionProperties;
10851284
1086impl Get<Properties> for CollectionProperties {1285impl Get<Properties> for CollectionProperties {
1089 }1288 }
1090}1289}
10911290
1291/// Utility struct for using in `StorageMap`.
1092pub struct TokenProperties;1292pub struct TokenProperties;
10931293
1094impl Get<Properties> for TokenProperties {1294impl Get<Properties> for TokenProperties {
modifiedprimitives/data-structs/src/mapping.rsdiffbeforeafterboth
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
2// This file is part of Unique Network.
3
4// Unique Network is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Unique Network is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// 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/>.
16
17//! This module contains mapping between different addresses.
18
1use core::marker::PhantomData;19use core::marker::PhantomData;
220
5use crate::{CollectionId, TokenId};23use crate::{CollectionId, TokenId};
6use pallet_evm::account::CrossAccountId;24use pallet_evm::account::CrossAccountId;
725
26/// Trait for mapping between token id and some `Address`.
8pub trait TokenAddressMapping<Address> {27pub trait TokenAddressMapping<Address> {
28 /// Map token id to `Address`.
9 fn token_to_address(collection: CollectionId, token: TokenId) -> Address;29 fn token_to_address(collection: CollectionId, token: TokenId) -> Address;
30
31 /// Map `Address` to token id.
10 fn address_to_token(address: &Address) -> Option<(CollectionId, TokenId)>;32 fn address_to_token(address: &Address) -> Option<(CollectionId, TokenId)>;
33
34 /// Check is address for token.
11 fn is_token_address(address: &Address) -> bool;35 fn is_token_address(address: &Address) -> bool;
12}36}
1337
38/// Unit struct for mapping token id to/from *Evm address* represented by [`H160`].
14pub struct EvmTokenAddressMapping;39pub struct EvmTokenAddressMapping;
1540
16/// 0xf8238ccfff8ed887463fd5e00000000100000002 - collection 1, token 241/// 0xf8238ccfff8ed887463fd5e00000000100000002 - collection 1, token 2
46 }71 }
47}72}
4873
74/// Unit struct for mapping token id to/from [`CrossAccountId`].
49pub struct CrossTokenAddressMapping<A>(PhantomData<A>);75pub struct CrossTokenAddressMapping<A>(PhantomData<A>);
5076
51impl<A, C: CrossAccountId<A>> TokenAddressMapping<C> for CrossTokenAddressMapping<A> {77impl<A, C: CrossAccountId<A>> TokenAddressMapping<C> for CrossTokenAddressMapping<A> {
modifiedprimitives/rpc/src/lib.rsdiffbeforeafterboth
2828
29sp_api::decl_runtime_apis! {29sp_api::decl_runtime_apis! {
30 #[api_version(2)]30 #[api_version(2)]
31 /// Trait for generate rpc.
31 pub trait UniqueApi<CrossAccountId, AccountId> where32 pub trait UniqueApi<CrossAccountId, AccountId> where
32 AccountId: Decode,33 AccountId: Decode,
33 CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,34 CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,
34 {35 {
35 #[changed_in(2)]36 #[changed_in(2)]
36 fn token_owner(collection: CollectionId, token: TokenId) -> Result<CrossAccountId>;37 fn token_owner(collection: CollectionId, token: TokenId) -> Result<CrossAccountId>;
3738
39 /// Get number of tokens in collection owned by account.
38 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>>;40 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>>;
41
42 /// Number of existing tokens in collection.
39 fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>>;43 fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>>;
44
45 /// Check token exist.
40 fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool>;46 fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool>;
4147
48 /// Get token owner.
42 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;49 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
50
51 /// Get real owner of nested token.
43 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;52 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
53
54 /// Get nested tokens for the specified item.
44 fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>>;55 fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>>;
4556
57 /// Get collection properties.
46 fn collection_properties(collection: CollectionId, properties: Option<Vec<Vec<u8>>>) -> Result<Vec<Property>>;58 fn collection_properties(collection: CollectionId, properties: Option<Vec<Vec<u8>>>) -> Result<Vec<Property>>;
4759
60 /// Get token properties.
48 fn token_properties(61 fn token_properties(
49 collection: CollectionId,62 collection: CollectionId,
50 token_id: TokenId,63 token_id: TokenId,
51 properties: Option<Vec<Vec<u8>>>64 properties: Option<Vec<Vec<u8>>>
52 ) -> Result<Vec<Property>>;65 ) -> Result<Vec<Property>>;
5366
67 /// Get permissions for token properties.
54 fn property_permissions(68 fn property_permissions(
55 collection: CollectionId,69 collection: CollectionId,
56 properties: Option<Vec<Vec<u8>>>70 properties: Option<Vec<Vec<u8>>>
57 ) -> Result<Vec<PropertyKeyPermission>>;71 ) -> Result<Vec<PropertyKeyPermission>>;
5872
73 /// Get token data.
59 fn token_data(74 fn token_data(
60 collection: CollectionId,75 collection: CollectionId,
61 token_id: TokenId,76 token_id: TokenId,
62 keys: Option<Vec<Vec<u8>>>77 keys: Option<Vec<Vec<u8>>>
63 ) -> Result<TokenData<CrossAccountId>>;78 ) -> Result<TokenData<CrossAccountId>>;
6479
80 /// Total number of tokens in collection.
65 fn total_supply(collection: CollectionId) -> Result<u32>;81 fn total_supply(collection: CollectionId) -> Result<u32>;
82
83 /// Get account balance for collection (sum of tokens pieces).
66 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32>;84 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32>;
85
86 /// Get account balance for specified token.
67 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128>;87 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128>;
88
89 /// Amount of token pieces allowed to spend from granded account.
68 fn allowance(90 fn allowance(
69 collection: CollectionId,91 collection: CollectionId,
70 sender: CrossAccountId,92 sender: CrossAccountId,
71 spender: CrossAccountId,93 spender: CrossAccountId,
72 token: TokenId,94 token: TokenId,
73 ) -> Result<u128>;95 ) -> Result<u128>;
7496
97 /// Get list of collection admins.
75 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>>;98 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>>;
99
100 /// Get list of users that allowet to mint tikens in collection.
76 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>>;101 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>>;
102
103 /// Check that user is in allowed list (see [`allowlist`]).
77 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool>;104 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool>;
105
106 /// Last minted token id.
78 fn last_token_id(collection: CollectionId) -> Result<TokenId>;107 fn last_token_id(collection: CollectionId) -> Result<TokenId>;
108
109 /// Get collection by id.
79 fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>>;110 fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>>;
111
112 /// Get collection stats.
80 fn collection_stats() -> Result<CollectionStats>;113 fn collection_stats() -> Result<CollectionStats>;
114
115 /// Get the number of blocks through which sponsorship will be available.
81 fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>>;116 fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>>;
117
118 /// Get effective colletion limits.
82 fn effective_collection_limits(collection_id: CollectionId) -> Result<Option<CollectionLimits>>;119 fn effective_collection_limits(collection_id: CollectionId) -> Result<Option<CollectionLimits>>;
120
121 /// Get total pieces of token.
83 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Result<Option<u128>>;122 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Result<Option<u128>>;
84 fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec<CrossAccountId>>;123 fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec<CrossAccountId>>;
85 }124 }