git.delta.rocks / unique-network / refs/commits / 7f8cc7f16d35

difftreelog

source

primitives/data-structs/src/lib.rs14.7 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	pallet_prelude::ConstU32,26};27use derivative::Derivative;28use scale_info::TypeInfo;2930mod migration;3132pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;33pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;34pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;3536pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {37	100_00038} else {39	1040};41pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {42	100_00043} else {44	1045};46pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {47	204848} else {49	1050};51pub const COLLECTION_ADMINS_LIMIT: u32 = 5;52pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;53pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {54	1_000_00055} else {56	1057};5859// Timeouts for item types in passed blocks60pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;61pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;62pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;6364pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;6566// Schema limits67pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;68pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;69pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;7071pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;72pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;73pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;7475/// How much items can be created per single76/// create_many call77pub const MAX_ITEMS_PER_BATCH: u32 = 200;7879parameter_types! {80	pub const CustomDataLimit: u32 = CUSTOM_DATA_LIMIT;81}8283#[derive(84	Encode,85	Decode,86	PartialEq,87	Eq,88	PartialOrd,89	Ord,90	Clone,91	Copy,92	Debug,93	Default,94	TypeInfo,95	MaxEncodedLen,96)]97#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]98pub struct CollectionId(pub u32);99impl EncodeLike<u32> for CollectionId {}100impl EncodeLike<CollectionId> for u32 {}101102#[derive(103	Encode,104	Decode,105	PartialEq,106	Eq,107	PartialOrd,108	Ord,109	Clone,110	Copy,111	Debug,112	Default,113	TypeInfo,114	MaxEncodedLen,115)]116#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]117pub struct TokenId(pub u32);118impl EncodeLike<u32> for TokenId {}119impl EncodeLike<TokenId> for u32 {}120121impl TokenId {122	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {123		self.0124			.checked_add(1)125			.ok_or(ArithmeticError::Overflow)126			.map(Self)127	}128}129130impl From<TokenId> for U256 {131	fn from(t: TokenId) -> Self {132		t.0.into()133	}134}135136impl TryFrom<U256> for TokenId {137	type Error = &'static str;138139	fn try_from(value: U256) -> Result<Self, Self::Error> {140		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))141	}142}143144pub struct OverflowError;145impl From<OverflowError> for &'static str {146	fn from(_: OverflowError) -> Self {147		"overflow occured"148	}149}150151pub type DecimalPoints = u8;152153#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]154#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]155pub enum CollectionMode {156	NFT,157	// decimal points158	Fungible(DecimalPoints),159	ReFungible,160}161162impl CollectionMode {163	pub fn id(&self) -> u8 {164		match self {165			CollectionMode::NFT => 1,166			CollectionMode::Fungible(_) => 2,167			CollectionMode::ReFungible => 3,168		}169	}170}171172pub trait SponsoringResolve<AccountId, Call> {173	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;174}175176#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]177#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]178pub enum AccessMode {179	Normal,180	AllowList,181}182impl Default for AccessMode {183	fn default() -> Self {184		Self::Normal185	}186}187188#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]189#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]190pub enum SchemaVersion {191	ImageURL,192	Unique,193}194impl Default for SchemaVersion {195	fn default() -> Self {196		Self::ImageURL197	}198}199200#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]201#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]202pub struct Ownership<AccountId> {203	pub owner: AccountId,204	pub fraction: u128,205}206207#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]208#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]209pub enum SponsorshipState<AccountId> {210	/// The fees are applied to the transaction sender211	Disabled,212	Unconfirmed(AccountId),213	/// Transactions are sponsored by specified account214	Confirmed(AccountId),215}216217impl<AccountId> SponsorshipState<AccountId> {218	pub fn sponsor(&self) -> Option<&AccountId> {219		match self {220			Self::Confirmed(sponsor) => Some(sponsor),221			_ => None,222		}223	}224225	pub fn pending_sponsor(&self) -> Option<&AccountId> {226		match self {227			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),228			_ => None,229		}230	}231232	pub fn confirmed(&self) -> bool {233		matches!(self, Self::Confirmed(_))234	}235}236237impl<T> Default for SponsorshipState<T> {238	fn default() -> Self {239		Self::Disabled240	}241}242243#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]244#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]245pub struct Collection<AccountId> {246	pub owner: AccountId,247	pub mode: CollectionMode,248	pub access: AccessMode,249	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]250	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,251	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]252	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,253	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]254	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,255	pub mint_mode: bool,256	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]257	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,258	pub schema_version: SchemaVersion,259	pub sponsorship: SponsorshipState<AccountId>,260	pub limits: CollectionLimits, // Collection private restrictions261	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]262	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,263	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]264	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,265	pub meta_update_permission: MetaUpdatePermission,266}267268#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative, MaxEncodedLen)]269#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]270#[derivative(Default(bound = ""))]271pub struct CreateCollectionData<AccountId> {272	#[derivative(Default(value = "CollectionMode::NFT"))]273	pub mode: CollectionMode,274	pub access: Option<AccessMode>,275	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]276	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,277	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]278	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,279	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]280	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,281	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]282	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,283	pub schema_version: Option<SchemaVersion>,284	pub pending_sponsor: Option<AccountId>,285	pub limits: Option<CollectionLimits>,286	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]287	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,288	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]289	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,290	pub meta_update_permission: Option<MetaUpdatePermission>,291}292293#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]294#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]295pub struct NftItemType<AccountId> {296	pub owner: AccountId,297	pub const_data: Vec<u8>,298	pub variable_data: Vec<u8>,299}300301#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]302#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]303pub struct FungibleItemType {304	pub value: u128,305}306307#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]308#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]309pub struct ReFungibleItemType<AccountId> {310	pub owner: Vec<Ownership<AccountId>>,311	pub const_data: Vec<u8>,312	pub variable_data: Vec<u8>,313}314315/// All fields are wrapped in `Option`s, where None means chain default316#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]317#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]318pub struct CollectionLimits {319	pub account_token_ownership_limit: Option<u32>,320	pub sponsored_data_size: Option<u32>,321	/// None - setVariableMetadata is not sponsored322	/// Some(v) - setVariableMetadata is sponsored323	///           if there is v block between txs324	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,325	pub token_limit: Option<u32>,326327	// Timeouts for item types in passed blocks328	pub sponsor_transfer_timeout: Option<u32>,329	pub sponsor_approve_timeout: Option<u32>,330	pub owner_can_transfer: Option<bool>,331	pub owner_can_destroy: Option<bool>,332	pub transfers_enabled: Option<bool>,333}334335impl CollectionLimits {336	pub fn account_token_ownership_limit(&self) -> u32 {337		self.account_token_ownership_limit338			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)339			.min(MAX_TOKEN_OWNERSHIP)340	}341	pub fn sponsored_data_size(&self) -> u32 {342		self.sponsored_data_size343			.unwrap_or(CUSTOM_DATA_LIMIT)344			.min(CUSTOM_DATA_LIMIT)345	}346	pub fn token_limit(&self) -> u32 {347		self.token_limit348			.unwrap_or(COLLECTION_TOKEN_LIMIT)349			.min(COLLECTION_TOKEN_LIMIT)350	}351	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {352		self.sponsor_transfer_timeout353			.unwrap_or(default)354			.min(MAX_SPONSOR_TIMEOUT)355	}356	pub fn sponsor_approve_timeout(&self) -> u32 {357		self.sponsor_approve_timeout358			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)359			.min(MAX_SPONSOR_TIMEOUT)360	}361	pub fn owner_can_transfer(&self) -> bool {362		self.owner_can_transfer.unwrap_or(true)363	}364	pub fn owner_can_destroy(&self) -> bool {365		self.owner_can_destroy.unwrap_or(true)366	}367	pub fn transfers_enabled(&self) -> bool {368		self.transfers_enabled.unwrap_or(true)369	}370	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {371		match self372			.sponsored_data_rate_limit373			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)374		{375			SponsoringRateLimit::SponsoringDisabled => None,376			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),377		}378	}379}380381#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]382#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]383pub enum SponsoringRateLimit {384	SponsoringDisabled,385	Blocks(u32),386}387388/// BoundedVec doesn't supports serde389#[cfg(feature = "serde1")]390mod bounded_serde {391	use core::convert::TryFrom;392	use frame_support::{BoundedVec, traits::Get};393	use serde::{394		ser::{self, Serialize},395		de::{self, Deserialize, Error},396	};397	use sp_std::vec::Vec;398399	pub fn serialize<D, V, S>(value: &BoundedVec<V, S>, serializer: D) -> Result<D::Ok, D::Error>400	where401		D: ser::Serializer,402		V: Serialize,403	{404		(value as &Vec<_>).serialize(serializer)405	}406407	pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>408	where409		D: de::Deserializer<'de>,410		V: de::Deserialize<'de>,411		S: Get<u32>,412	{413		// TODO: Implement custom visitor, which will limit vec size at parse time? Will serde only be used by chainspec?414		let vec = <Vec<V>>::deserialize(deserializer)?;415		let len = vec.len();416		TryFrom::try_from(vec).map_err(|_| D::Error::invalid_length(len, &"lesser size"))417	}418}419420#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]421#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]422#[derivative(Debug)]423pub struct CreateNftData {424	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]425	#[derivative(Debug = "ignore")]426	pub const_data: BoundedVec<u8, CustomDataLimit>,427	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]428	#[derivative(Debug = "ignore")]429	pub variable_data: BoundedVec<u8, CustomDataLimit>,430}431432#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]433#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]434pub struct CreateFungibleData {435	pub value: u128,436}437438#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]439#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]440#[derivative(Debug)]441pub struct CreateReFungibleData {442	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]443	#[derivative(Debug = "ignore")]444	pub const_data: BoundedVec<u8, CustomDataLimit>,445	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]446	#[derivative(Debug = "ignore")]447	pub variable_data: BoundedVec<u8, CustomDataLimit>,448	pub pieces: u128,449}450451#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]452#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]453pub enum MetaUpdatePermission {454	ItemOwner,455	Admin,456	None,457}458459impl Default for MetaUpdatePermission {460	fn default() -> Self {461		Self::ItemOwner462	}463}464465#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]466#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]467pub enum CreateItemData {468	NFT(CreateNftData),469	Fungible(CreateFungibleData),470	ReFungible(CreateReFungibleData),471}472473impl CreateItemData {474	pub fn data_size(&self) -> usize {475		match self {476			CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),477			CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),478			_ => 0,479		}480	}481}482483impl From<CreateNftData> for CreateItemData {484	fn from(item: CreateNftData) -> Self {485		CreateItemData::NFT(item)486	}487}488489impl From<CreateReFungibleData> for CreateItemData {490	fn from(item: CreateReFungibleData) -> Self {491		CreateItemData::ReFungible(item)492	}493}494495impl From<CreateFungibleData> for CreateItemData {496	fn from(item: CreateFungibleData) -> Self {497		CreateItemData::Fungible(item)498	}499}500501#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]502#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]503pub struct CollectionStats {504	pub created: u32,505	pub destroyed: u32,506	pub alive: u32,507}