git.delta.rocks / unique-network / refs/commits / 12cd6cb586e3

difftreelog

source

primitives/data-structs/src/lib.rs17.8 KiBsourcehistory
1#![cfg_attr(not(feature = "std"), no_std)]23use core::{4	convert::{TryFrom, TryInto},5	fmt,6};7use frame_support::storage::bounded_btree_map::BoundedBTreeMap;8use sp_std::collections::btree_map::BTreeMap;910#[cfg(feature = "serde")]11pub use serde::{Serialize, Deserialize};1213use sp_core::U256;14use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};15use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};16pub use frame_support::{17	BoundedVec, construct_runtime, decl_event, decl_module, decl_storage, decl_error,18	dispatch::DispatchResult,19	ensure, fail, parameter_types,20	traits::{21		Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,22		Randomness, IsSubType, WithdrawReasons,23	},24	weights::{25		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},26		DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,27		WeightToFeePolynomial, DispatchClass,28	},29	StorageValue, transactional,30	pallet_prelude::ConstU32,31};32use derivative::Derivative;33use scale_info::TypeInfo;3435mod migration;3637pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;38pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;39pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;4041pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {42	100_00043} else {44	1045};46pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {47	100_00048} else {49	1050};51pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {52	204853} else {54	1055};56pub const COLLECTION_ADMINS_LIMIT: u32 = 5;57pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;58pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {59	1_000_00060} else {61	1062};6364// Timeouts for item types in passed blocks65pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;66pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;67pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;6869pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;7071// Schema limits72pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;73pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;74pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;7576pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;77pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;78pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;7980/// How much items can be created per single81/// create_many call82pub const MAX_ITEMS_PER_BATCH: u32 = 200;8384pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;8586#[derive(87	Encode,88	Decode,89	PartialEq,90	Eq,91	PartialOrd,92	Ord,93	Clone,94	Copy,95	Debug,96	Default,97	TypeInfo,98	MaxEncodedLen,99)]100#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]101pub struct CollectionId(pub u32);102impl EncodeLike<u32> for CollectionId {}103impl EncodeLike<CollectionId> for u32 {}104105#[derive(106	Encode,107	Decode,108	PartialEq,109	Eq,110	PartialOrd,111	Ord,112	Clone,113	Copy,114	Debug,115	Default,116	TypeInfo,117	MaxEncodedLen,118)]119#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]120pub struct TokenId(pub u32);121impl EncodeLike<u32> for TokenId {}122impl EncodeLike<TokenId> for u32 {}123124impl TokenId {125	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {126		self.0127			.checked_add(1)128			.ok_or(ArithmeticError::Overflow)129			.map(Self)130	}131}132133impl From<TokenId> for U256 {134	fn from(t: TokenId) -> Self {135		t.0.into()136	}137}138139impl TryFrom<U256> for TokenId {140	type Error = &'static str;141142	fn try_from(value: U256) -> Result<Self, Self::Error> {143		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))144	}145}146147pub struct OverflowError;148impl From<OverflowError> for &'static str {149	fn from(_: OverflowError) -> Self {150		"overflow occured"151	}152}153154pub type DecimalPoints = u8;155156#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]157#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]158pub enum CollectionMode {159	NFT,160	// decimal points161	Fungible(DecimalPoints),162	ReFungible,163}164165impl CollectionMode {166	pub fn id(&self) -> u8 {167		match self {168			CollectionMode::NFT => 1,169			CollectionMode::Fungible(_) => 2,170			CollectionMode::ReFungible => 3,171		}172	}173}174175pub trait SponsoringResolve<AccountId, Call> {176	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;177}178179#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]180#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]181pub enum AccessMode {182	Normal,183	AllowList,184}185impl Default for AccessMode {186	fn default() -> Self {187		Self::Normal188	}189}190191#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]192#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]193pub enum SchemaVersion {194	ImageURL,195	Unique,196}197impl Default for SchemaVersion {198	fn default() -> Self {199		Self::ImageURL200	}201}202203#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]204#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]205pub struct Ownership<AccountId> {206	pub owner: AccountId,207	pub fraction: u128,208}209210#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]211#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]212pub enum SponsorshipState<AccountId> {213	/// The fees are applied to the transaction sender214	Disabled,215	Unconfirmed(AccountId),216	/// Transactions are sponsored by specified account217	Confirmed(AccountId),218}219220impl<AccountId> SponsorshipState<AccountId> {221	pub fn sponsor(&self) -> Option<&AccountId> {222		match self {223			Self::Confirmed(sponsor) => Some(sponsor),224			_ => None,225		}226	}227228	pub fn pending_sponsor(&self) -> Option<&AccountId> {229		match self {230			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),231			_ => None,232		}233	}234235	pub fn confirmed(&self) -> bool {236		matches!(self, Self::Confirmed(_))237	}238}239240impl<T> Default for SponsorshipState<T> {241	fn default() -> Self {242		Self::Disabled243	}244}245246#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]247#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]248pub struct Collection<AccountId> {249	pub owner: AccountId,250	pub mode: CollectionMode,251	pub access: AccessMode,252	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]253	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,254	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]255	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,256	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]257	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,258	pub mint_mode: bool,259	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]260	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,261	pub schema_version: SchemaVersion,262	pub sponsorship: SponsorshipState<AccountId>,263	pub limits: CollectionLimits, // Collection private restrictions264	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]265	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,266	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]267	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,268	pub meta_update_permission: MetaUpdatePermission,269}270271#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative, MaxEncodedLen)]272#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]273#[derivative(Default(bound = ""))]274pub struct CreateCollectionData<AccountId> {275	#[derivative(Default(value = "CollectionMode::NFT"))]276	pub mode: CollectionMode,277	pub access: Option<AccessMode>,278	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]279	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,280	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]281	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,282	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]283	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,284	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]285	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,286	pub schema_version: Option<SchemaVersion>,287	pub pending_sponsor: Option<AccountId>,288	pub limits: Option<CollectionLimits>,289	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]290	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,291	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]292	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,293	pub meta_update_permission: Option<MetaUpdatePermission>,294}295296#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]297#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]298pub struct NftItemType<AccountId> {299	pub owner: AccountId,300	pub const_data: Vec<u8>,301	pub variable_data: Vec<u8>,302}303304#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]305#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]306pub struct FungibleItemType {307	pub value: u128,308}309310#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]311#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]312pub struct ReFungibleItemType<AccountId> {313	pub owner: Vec<Ownership<AccountId>>,314	pub const_data: Vec<u8>,315	pub variable_data: Vec<u8>,316}317318/// All fields are wrapped in `Option`s, where None means chain default319#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]320#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]321pub struct CollectionLimits {322	pub account_token_ownership_limit: Option<u32>,323	pub sponsored_data_size: Option<u32>,324	/// None - setVariableMetadata is not sponsored325	/// Some(v) - setVariableMetadata is sponsored326	///           if there is v block between txs327	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,328	pub token_limit: Option<u32>,329330	// Timeouts for item types in passed blocks331	pub sponsor_transfer_timeout: Option<u32>,332	pub sponsor_approve_timeout: Option<u32>,333	pub owner_can_transfer: Option<bool>,334	pub owner_can_destroy: Option<bool>,335	pub transfers_enabled: Option<bool>,336}337338impl CollectionLimits {339	pub fn account_token_ownership_limit(&self) -> u32 {340		self.account_token_ownership_limit341			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)342			.min(MAX_TOKEN_OWNERSHIP)343	}344	pub fn sponsored_data_size(&self) -> u32 {345		self.sponsored_data_size346			.unwrap_or(CUSTOM_DATA_LIMIT)347			.min(CUSTOM_DATA_LIMIT)348	}349	pub fn token_limit(&self) -> u32 {350		self.token_limit351			.unwrap_or(COLLECTION_TOKEN_LIMIT)352			.min(COLLECTION_TOKEN_LIMIT)353	}354	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {355		self.sponsor_transfer_timeout356			.unwrap_or(default)357			.min(MAX_SPONSOR_TIMEOUT)358	}359	pub fn sponsor_approve_timeout(&self) -> u32 {360		self.sponsor_approve_timeout361			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)362			.min(MAX_SPONSOR_TIMEOUT)363	}364	pub fn owner_can_transfer(&self) -> bool {365		self.owner_can_transfer.unwrap_or(true)366	}367	pub fn owner_can_destroy(&self) -> bool {368		self.owner_can_destroy.unwrap_or(true)369	}370	pub fn transfers_enabled(&self) -> bool {371		self.transfers_enabled.unwrap_or(true)372	}373	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {374		match self375			.sponsored_data_rate_limit376			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)377		{378			SponsoringRateLimit::SponsoringDisabled => None,379			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),380		}381	}382}383384#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]385#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]386pub enum SponsoringRateLimit {387	SponsoringDisabled,388	Blocks(u32),389}390391/// BoundedVec doesn't supports serde392#[cfg(feature = "serde1")]393mod bounded_serde {394	use core::convert::TryFrom;395	use frame_support::{BoundedVec, traits::Get};396	use serde::{397		ser::{self, Serialize},398		de::{self, Deserialize, Error},399	};400	use sp_std::vec::Vec;401402	pub fn serialize<D, V, S>(value: &BoundedVec<V, S>, serializer: D) -> Result<D::Ok, D::Error>403	where404		D: ser::Serializer,405		V: Serialize,406	{407		(value as &Vec<_>).serialize(serializer)408	}409410	pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>411	where412		D: de::Deserializer<'de>,413		V: de::Deserialize<'de>,414		S: Get<u32>,415	{416		// TODO: Implement custom visitor, which will limit vec size at parse time? Will serde only be used by chainspec?417		let vec = <Vec<V>>::deserialize(deserializer)?;418		let len = vec.len();419		TryFrom::try_from(vec).map_err(|_| D::Error::invalid_length(len, &"lesser size"))420	}421}422423fn bounded_debug<V, S>(v: &BoundedVec<V, S>, f: &mut fmt::Formatter) -> Result<(), fmt::Error>424where425	V: fmt::Debug,426{427	use core::fmt::Debug;428	(&v as &Vec<V>).fmt(f)429}430431#[cfg(feature = "serde1")]432#[allow(dead_code)]433mod bounded_map_serde {434	use core::convert::TryFrom;435	use sp_std::collections::btree_map::BTreeMap;436	use frame_support::{traits::Get, storage::bounded_btree_map::BoundedBTreeMap};437	use serde::{438		ser::{self, Serialize},439		de::{self, Deserialize, Error},440	};441	pub fn serialize<D, K, V, S>(442		value: &BoundedBTreeMap<K, V, S>,443		serializer: D,444	) -> Result<D::Ok, D::Error>445	where446		D: ser::Serializer,447		K: Serialize + Ord,448		V: Serialize,449	{450		(value as &BTreeMap<_, _>).serialize(serializer)451	}452453	pub fn deserialize<'de, D, K, V, S>(454		deserializer: D,455	) -> Result<BoundedBTreeMap<K, V, S>, D::Error>456	where457		D: de::Deserializer<'de>,458		K: de::Deserialize<'de> + Ord,459		V: de::Deserialize<'de>,460		S: Get<u32>,461	{462		let map = <BTreeMap<K, V>>::deserialize(deserializer)?;463		let len = map.len();464		TryFrom::try_from(map).map_err(|_| D::Error::invalid_length(len, &"lesser size"))465	}466}467468fn bounded_map_debug<K, V, S>(469	v: &BoundedBTreeMap<K, V, S>,470	f: &mut fmt::Formatter,471) -> Result<(), fmt::Error>472where473	K: fmt::Debug + Ord,474	V: fmt::Debug,475{476	use core::fmt::Debug;477	(&v as &BTreeMap<K, V>).fmt(f)478}479480#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]481#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]482#[derivative(Debug)]483pub struct CreateNftData {484	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]485	#[derivative(Debug(format_with = "bounded_debug"))]486	pub const_data: BoundedVec<u8, CustomDataLimit>,487	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]488	#[derivative(Debug(format_with = "bounded_debug"))]489	pub variable_data: BoundedVec<u8, CustomDataLimit>,490}491492#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]493#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]494pub struct CreateFungibleData {495	pub value: u128,496}497498#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]499#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]500#[derivative(Debug)]501pub struct CreateReFungibleData {502	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]503	#[derivative(Debug(format_with = "bounded_debug"))]504	pub const_data: BoundedVec<u8, CustomDataLimit>,505	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]506	#[derivative(Debug(format_with = "bounded_debug"))]507	pub variable_data: BoundedVec<u8, CustomDataLimit>,508	pub pieces: u128,509}510511#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]512#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]513pub enum MetaUpdatePermission {514	ItemOwner,515	Admin,516	None,517}518519impl Default for MetaUpdatePermission {520	fn default() -> Self {521		Self::ItemOwner522	}523}524525#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]526#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]527pub enum CreateItemData {528	NFT(CreateNftData),529	Fungible(CreateFungibleData),530	ReFungible(CreateReFungibleData),531}532533#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]534#[derivative(Debug)]535pub struct CreateNftExData<CrossAccountId> {536	#[derivative(Debug(format_with = "bounded_debug"))]537	pub const_data: BoundedVec<u8, CustomDataLimit>,538	#[derivative(Debug(format_with = "bounded_debug"))]539	pub variable_data: BoundedVec<u8, CustomDataLimit>,540	pub owner: CrossAccountId,541}542543#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]544#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]545pub struct CreateRefungibleExData<CrossAccountId> {546	#[derivative(Debug(format_with = "bounded_debug"))]547	pub const_data: BoundedVec<u8, CustomDataLimit>,548	#[derivative(Debug(format_with = "bounded_debug"))]549	pub variable_data: BoundedVec<u8, CustomDataLimit>,550	#[derivative(Debug(format_with = "bounded_map_debug"))]551	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,552}553554#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]555#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]556pub enum CreateItemExData<CrossAccountId> {557	NFT(558		#[derivative(Debug(format_with = "bounded_debug"))]559		BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,560	),561	Fungible(562		#[derivative(Debug(format_with = "bounded_map_debug"))]563		BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,564	),565	/// Many tokens, each may have only one owner566	RefungibleMultipleItems(567		#[derivative(Debug(format_with = "bounded_debug"))]568		BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,569	),570	/// Single token, which may have many owners571	RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),572}573574impl CreateItemData {575	pub fn data_size(&self) -> usize {576		match self {577			CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),578			CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),579			_ => 0,580		}581	}582}583584impl From<CreateNftData> for CreateItemData {585	fn from(item: CreateNftData) -> Self {586		CreateItemData::NFT(item)587	}588}589590impl From<CreateReFungibleData> for CreateItemData {591	fn from(item: CreateReFungibleData) -> Self {592		CreateItemData::ReFungible(item)593	}594}595596impl From<CreateFungibleData> for CreateItemData {597	fn from(item: CreateFungibleData) -> Self {598		CreateItemData::Fungible(item)599	}600}601602#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]603#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]604pub struct CollectionStats {605	pub created: u32,606	pub destroyed: u32,607	pub alive: u32,608}