git.delta.rocks / unique-network / refs/commits / e637581b59d0

difftreelog

source

primitives/data-structs/src/lib.rs12.9 KiBsourcehistory
1#![cfg_attr(not(feature = "std"), no_std)]23use core::convert::{TryFrom, TryInto};45#[cfg(feature = "serde")]6pub use serde::{Serialize, Deserialize};78use sp_core::U256;9use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};10use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};11pub use frame_support::{12	BoundedVec, construct_runtime, decl_event, decl_module, decl_storage, decl_error,13	dispatch::DispatchResult,14	ensure, fail, parameter_types,15	traits::{16		Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,17		Randomness, IsSubType, WithdrawReasons,18	},19	weights::{20		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},21		DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,22		WeightToFeePolynomial, DispatchClass,23	},24	StorageValue, transactional,25};26use derivative::Derivative;27use scale_info::TypeInfo;2829pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;30pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;31pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;3233pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {34	100_00035} else {36	1037};38pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {39	100_00040} else {41	1042};43pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {44	204845} else {46	1047};48pub const COLLECTION_ADMINS_LIMIT: u32 = 5;49pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;50pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {51	1_000_00052} else {53	1054};5556// Timeouts for item types in passed blocks57pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;58pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;59pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;6061pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;6263// Schema limits64pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;65pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;66pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 1048576;6768pub const MAX_COLLECTION_NAME_LENGTH: usize = 64;69pub const MAX_COLLECTION_DESCRIPTION_LENGTH: usize = 256;70pub const MAX_TOKEN_PREFIX_LENGTH: usize = 16;7172/// How much items can be created per single73/// create_many call74pub const MAX_ITEMS_PER_BATCH: u32 = 200;7576parameter_types! {77	pub const CustomDataLimit: u32 = CUSTOM_DATA_LIMIT;78}7980#[derive(Encode, Decode, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default, TypeInfo)]81#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]82pub struct CollectionId(pub u32);83impl EncodeLike<u32> for CollectionId {}84impl EncodeLike<CollectionId> for u32 {}8586#[derive(Encode, Decode, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default, TypeInfo)]87#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]88pub struct TokenId(pub u32);89impl EncodeLike<u32> for TokenId {}90impl EncodeLike<TokenId> for u32 {}9192impl TokenId {93	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {94		self.095			.checked_add(1)96			.ok_or(ArithmeticError::Overflow)97			.map(Self)98	}99}100101impl From<TokenId> for U256 {102	fn from(t: TokenId) -> Self {103		t.0.into()104	}105}106107impl TryFrom<U256> for TokenId {108	type Error = &'static str;109110	fn try_from(value: U256) -> Result<Self, Self::Error> {111		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))112	}113}114115pub struct OverflowError;116impl From<OverflowError> for &'static str {117	fn from(_: OverflowError) -> Self {118		"overflow occured"119	}120}121122pub type DecimalPoints = u8;123124#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo)]125#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]126pub enum CollectionMode {127	NFT,128	// decimal points129	Fungible(DecimalPoints),130	ReFungible,131}132133impl CollectionMode {134	pub fn id(&self) -> u8 {135		match self {136			CollectionMode::NFT => 1,137			CollectionMode::Fungible(_) => 2,138			CollectionMode::ReFungible => 3,139		}140	}141}142143pub trait SponsoringResolve<AccountId, Call> {144	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;145}146147#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo)]148#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]149pub enum AccessMode {150	Normal,151	AllowList,152}153impl Default for AccessMode {154	fn default() -> Self {155		Self::Normal156	}157}158159#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo)]160#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]161pub enum SchemaVersion {162	ImageURL,163	Unique,164}165impl Default for SchemaVersion {166	fn default() -> Self {167		Self::ImageURL168	}169}170171#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]172#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]173pub struct Ownership<AccountId> {174	pub owner: AccountId,175	pub fraction: u128,176}177178#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]179#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]180pub enum SponsorshipState<AccountId> {181	/// The fees are applied to the transaction sender182	Disabled,183	Unconfirmed(AccountId),184	/// Transactions are sponsored by specified account185	Confirmed(AccountId),186}187188impl<AccountId> SponsorshipState<AccountId> {189	pub fn sponsor(&self) -> Option<&AccountId> {190		match self {191			Self::Confirmed(sponsor) => Some(sponsor),192			_ => None,193		}194	}195196	pub fn pending_sponsor(&self) -> Option<&AccountId> {197		match self {198			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),199			_ => None,200		}201	}202203	pub fn confirmed(&self) -> bool {204		matches!(self, Self::Confirmed(_))205	}206}207208impl<T> Default for SponsorshipState<T> {209	fn default() -> Self {210		Self::Disabled211	}212}213214#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]215#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]216pub struct Collection<AccountId> {217	pub owner: AccountId,218	pub mode: CollectionMode,219	pub access: AccessMode,220	pub name: Vec<u16>,        // 64 include null escape char221	pub description: Vec<u16>, // 256 include null escape char222	pub token_prefix: Vec<u8>, // 16 include null escape char223	pub mint_mode: bool,224	pub offchain_schema: Vec<u8>,225	pub schema_version: SchemaVersion,226	pub sponsorship: SponsorshipState<AccountId>,227	pub limits: CollectionLimits,          // Collection private restrictions228	pub variable_on_chain_schema: Vec<u8>, //229	pub const_on_chain_schema: Vec<u8>,    //230	pub meta_update_permission: MetaUpdatePermission,231}232233#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative)]234#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]235#[derivative(Default)]236pub struct CreateCollectionData<AccountId> {237	#[derivative(Default(value = "CollectionMode::NFT"))]238	pub mode: CollectionMode,239	pub access: Option<AccessMode>,240	pub name: Vec<u16>,241	pub description: Vec<u16>,242	pub token_prefix: Vec<u8>,243	pub offchain_schema: Vec<u8>,244	pub schema_version: Option<SchemaVersion>,245	pub pending_sponsor: Option<AccountId>,246	pub limits: Option<CollectionLimits>,247	pub variable_on_chain_schema: Vec<u8>,248	pub const_on_chain_schema: Vec<u8>,249	pub meta_update_permission: Option<MetaUpdatePermission>,250}251252#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]253#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]254pub struct NftItemType<AccountId> {255	pub owner: AccountId,256	pub const_data: Vec<u8>,257	pub variable_data: Vec<u8>,258}259260#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]261#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]262pub struct FungibleItemType {263	pub value: u128,264}265266#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]267#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]268pub struct ReFungibleItemType<AccountId> {269	pub owner: Vec<Ownership<AccountId>>,270	pub const_data: Vec<u8>,271	pub variable_data: Vec<u8>,272}273274/// All fields are wrapped in `Option`s, where None means chain default275#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo)]276#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]277pub struct CollectionLimits {278	pub account_token_ownership_limit: Option<u32>,279	pub sponsored_data_size: Option<u32>,280	/// None - setVariableMetadata is not sponsored281	/// Some(v) - setVariableMetadata is sponsored282	///           if there is v block between txs283	pub sponsored_data_rate_limit: Option<(Option<u32>,)>,284	pub token_limit: Option<u32>,285286	// Timeouts for item types in passed blocks287	pub sponsor_transfer_timeout: Option<u32>,288	pub sponsor_approve_timeout: Option<u32>,289	pub owner_can_transfer: Option<bool>,290	pub owner_can_destroy: Option<bool>,291	pub transfers_enabled: Option<bool>,292}293294impl CollectionLimits {295	pub fn account_token_ownership_limit(&self) -> u32 {296		self.account_token_ownership_limit297			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)298			.min(MAX_TOKEN_OWNERSHIP)299	}300	pub fn sponsored_data_size(&self) -> u32 {301		self.sponsored_data_size302			.unwrap_or(CUSTOM_DATA_LIMIT)303			.min(CUSTOM_DATA_LIMIT)304	}305	pub fn token_limit(&self) -> u32 {306		self.token_limit307			.unwrap_or(COLLECTION_TOKEN_LIMIT)308			.min(COLLECTION_TOKEN_LIMIT)309	}310	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {311		self.sponsor_transfer_timeout312			.unwrap_or(default)313			.min(MAX_SPONSOR_TIMEOUT)314	}315	pub fn sponsor_approve_timeout(&self) -> u32 {316		self.sponsor_approve_timeout317			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)318			.min(MAX_SPONSOR_TIMEOUT)319	}320	pub fn owner_can_transfer(&self) -> bool {321		self.owner_can_transfer.unwrap_or(true)322	}323	pub fn owner_can_destroy(&self) -> bool {324		self.owner_can_destroy.unwrap_or(true)325	}326	pub fn transfers_enabled(&self) -> bool {327		self.transfers_enabled.unwrap_or(true)328	}329	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {330		self.sponsored_data_rate_limit331			.unwrap_or((None,))332			.0333			.map(|v| v.min(MAX_SPONSOR_TIMEOUT))334	}335}336337/// BoundedVec doesn't supports serde338#[cfg(feature = "serde1")]339mod bounded_serde {340	use core::convert::TryFrom;341	use frame_support::{BoundedVec, traits::Get};342	use serde::{343		ser::{self, Serialize},344		de::{self, Deserialize, Error},345	};346	use sp_std::vec::Vec;347348	pub fn serialize<D, V, S>(value: &BoundedVec<V, S>, serializer: D) -> Result<D::Ok, D::Error>349	where350		D: ser::Serializer,351		V: Serialize,352	{353		(value as &Vec<_>).serialize(serializer)354	}355356	pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>357	where358		D: de::Deserializer<'de>,359		V: de::Deserialize<'de>,360		S: Get<u32>,361	{362		// TODO: Implement custom visitor, which will limit vec size at parse time? Will serde only be used by chainspec?363		let vec = <Vec<V>>::deserialize(deserializer)?;364		let len = vec.len();365		TryFrom::try_from(vec).map_err(|_| D::Error::invalid_length(len, &"lesser size"))366	}367}368369#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]370#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]371#[derivative(Debug)]372pub struct CreateNftData {373	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]374	#[derivative(Debug = "ignore")]375	pub const_data: BoundedVec<u8, CustomDataLimit>,376	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]377	#[derivative(Debug = "ignore")]378	pub variable_data: BoundedVec<u8, CustomDataLimit>,379}380381#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]382#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]383pub struct CreateFungibleData {384	pub value: u128,385}386387#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]388#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]389#[derivative(Debug)]390pub struct CreateReFungibleData {391	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]392	#[derivative(Debug = "ignore")]393	pub const_data: BoundedVec<u8, CustomDataLimit>,394	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]395	#[derivative(Debug = "ignore")]396	pub variable_data: BoundedVec<u8, CustomDataLimit>,397	pub pieces: u128,398}399400#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]401#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]402pub enum MetaUpdatePermission {403	ItemOwner,404	Admin,405	None,406}407408impl Default for MetaUpdatePermission {409	fn default() -> Self {410		Self::ItemOwner411	}412}413414#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]415#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]416pub enum CreateItemData {417	NFT(CreateNftData),418	Fungible(CreateFungibleData),419	ReFungible(CreateReFungibleData),420}421422impl CreateItemData {423	pub fn data_size(&self) -> usize {424		match self {425			CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),426			CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),427			_ => 0,428		}429	}430}431432impl From<CreateNftData> for CreateItemData {433	fn from(item: CreateNftData) -> Self {434		CreateItemData::NFT(item)435	}436}437438impl From<CreateReFungibleData> for CreateItemData {439	fn from(item: CreateReFungibleData) -> Self {440		CreateItemData::ReFungible(item)441	}442}443444impl From<CreateFungibleData> for CreateItemData {445	fn from(item: CreateFungibleData) -> Self {446		CreateItemData::Fungible(item)447	}448}449450#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]451#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]452pub struct CollectionStats {453	pub created: u32,454	pub destroyed: u32,455	pub alive: u32,456}