git.delta.rocks / unique-network / refs/commits / 73817f448a72

difftreelog

source

primitives/data-structs/src/lib.rs16.0 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;7879pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;8081#[derive(82	Encode,83	Decode,84	PartialEq,85	Eq,86	PartialOrd,87	Ord,88	Clone,89	Copy,90	Debug,91	Default,92	TypeInfo,93	MaxEncodedLen,94)]95#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]96pub struct CollectionId(pub u32);97impl EncodeLike<u32> for CollectionId {}98impl EncodeLike<CollectionId> for u32 {}99100#[derive(101	Encode,102	Decode,103	PartialEq,104	Eq,105	PartialOrd,106	Ord,107	Clone,108	Copy,109	Debug,110	Default,111	TypeInfo,112	MaxEncodedLen,113)]114#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]115pub struct TokenId(pub u32);116impl EncodeLike<u32> for TokenId {}117impl EncodeLike<TokenId> for u32 {}118119impl TokenId {120	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {121		self.0122			.checked_add(1)123			.ok_or(ArithmeticError::Overflow)124			.map(Self)125	}126}127128impl From<TokenId> for U256 {129	fn from(t: TokenId) -> Self {130		t.0.into()131	}132}133134impl TryFrom<U256> for TokenId {135	type Error = &'static str;136137	fn try_from(value: U256) -> Result<Self, Self::Error> {138		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))139	}140}141142pub struct OverflowError;143impl From<OverflowError> for &'static str {144	fn from(_: OverflowError) -> Self {145		"overflow occured"146	}147}148149pub type DecimalPoints = u8;150151#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]152#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]153pub enum CollectionMode {154	NFT,155	// decimal points156	Fungible(DecimalPoints),157	ReFungible,158}159160impl CollectionMode {161	pub fn id(&self) -> u8 {162		match self {163			CollectionMode::NFT => 1,164			CollectionMode::Fungible(_) => 2,165			CollectionMode::ReFungible => 3,166		}167	}168}169170pub trait SponsoringResolve<AccountId, Call> {171	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;172}173174#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]175#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]176pub enum AccessMode {177	Normal,178	AllowList,179}180impl Default for AccessMode {181	fn default() -> Self {182		Self::Normal183	}184}185186#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]187#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]188pub enum SchemaVersion {189	ImageURL,190	Unique,191}192impl Default for SchemaVersion {193	fn default() -> Self {194		Self::ImageURL195	}196}197198#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]199#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]200pub struct Ownership<AccountId> {201	pub owner: AccountId,202	pub fraction: u128,203}204205#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]206#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]207pub enum SponsorshipState<AccountId> {208	/// The fees are applied to the transaction sender209	Disabled,210	Unconfirmed(AccountId),211	/// Transactions are sponsored by specified account212	Confirmed(AccountId),213}214215impl<AccountId> SponsorshipState<AccountId> {216	pub fn sponsor(&self) -> Option<&AccountId> {217		match self {218			Self::Confirmed(sponsor) => Some(sponsor),219			_ => None,220		}221	}222223	pub fn pending_sponsor(&self) -> Option<&AccountId> {224		match self {225			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),226			_ => None,227		}228	}229230	pub fn confirmed(&self) -> bool {231		matches!(self, Self::Confirmed(_))232	}233}234235impl<T> Default for SponsorshipState<T> {236	fn default() -> Self {237		Self::Disabled238	}239}240241#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]242#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]243pub struct Collection<AccountId> {244	pub owner: AccountId,245	pub mode: CollectionMode,246	pub access: AccessMode,247	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]248	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,249	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]250	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,251	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]252	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,253	pub mint_mode: bool,254	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]255	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,256	pub schema_version: SchemaVersion,257	pub sponsorship: SponsorshipState<AccountId>,258	pub limits: CollectionLimits, // Collection private restrictions259	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]260	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,261	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]262	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,263	pub meta_update_permission: MetaUpdatePermission,264}265266#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Debug, Derivative, MaxEncodedLen)]267#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]268#[derivative(Default(bound = ""))]269pub struct CreateCollectionData<AccountId> {270	#[derivative(Default(value = "CollectionMode::NFT"))]271	pub mode: CollectionMode,272	pub access: Option<AccessMode>,273	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]274	pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,275	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]276	pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,277	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]278	pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,279	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]280	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,281	pub schema_version: Option<SchemaVersion>,282	pub pending_sponsor: Option<AccountId>,283	pub limits: Option<CollectionLimits>,284	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]285	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,286	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]287	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,288	pub meta_update_permission: Option<MetaUpdatePermission>,289}290291#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]292#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]293pub struct NftItemType<AccountId> {294	pub owner: AccountId,295	pub const_data: Vec<u8>,296	pub variable_data: Vec<u8>,297}298299#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]300#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]301pub struct FungibleItemType {302	pub value: u128,303}304305#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]306#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]307pub struct ReFungibleItemType<AccountId> {308	pub owner: Vec<Ownership<AccountId>>,309	pub const_data: Vec<u8>,310	pub variable_data: Vec<u8>,311}312313/// All fields are wrapped in `Option`s, where None means chain default314#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]315#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]316pub struct CollectionLimits {317	pub account_token_ownership_limit: Option<u32>,318	pub sponsored_data_size: Option<u32>,319	/// None - setVariableMetadata is not sponsored320	/// Some(v) - setVariableMetadata is sponsored321	///           if there is v block between txs322	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,323	pub token_limit: Option<u32>,324325	// Timeouts for item types in passed blocks326	pub sponsor_transfer_timeout: Option<u32>,327	pub sponsor_approve_timeout: Option<u32>,328	pub owner_can_transfer: Option<bool>,329	pub owner_can_destroy: Option<bool>,330	pub transfers_enabled: Option<bool>,331}332333impl CollectionLimits {334	pub fn account_token_ownership_limit(&self) -> u32 {335		self.account_token_ownership_limit336			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)337			.min(MAX_TOKEN_OWNERSHIP)338	}339	pub fn sponsored_data_size(&self) -> u32 {340		self.sponsored_data_size341			.unwrap_or(CUSTOM_DATA_LIMIT)342			.min(CUSTOM_DATA_LIMIT)343	}344	pub fn token_limit(&self) -> u32 {345		self.token_limit346			.unwrap_or(COLLECTION_TOKEN_LIMIT)347			.min(COLLECTION_TOKEN_LIMIT)348	}349	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {350		self.sponsor_transfer_timeout351			.unwrap_or(default)352			.min(MAX_SPONSOR_TIMEOUT)353	}354	pub fn sponsor_approve_timeout(&self) -> u32 {355		self.sponsor_approve_timeout356			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)357			.min(MAX_SPONSOR_TIMEOUT)358	}359	pub fn owner_can_transfer(&self) -> bool {360		self.owner_can_transfer.unwrap_or(true)361	}362	pub fn owner_can_destroy(&self) -> bool {363		self.owner_can_destroy.unwrap_or(true)364	}365	pub fn transfers_enabled(&self) -> bool {366		self.transfers_enabled.unwrap_or(true)367	}368	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {369		match self370			.sponsored_data_rate_limit371			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)372		{373			SponsoringRateLimit::SponsoringDisabled => None,374			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),375		}376	}377}378379#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]380#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]381pub enum SponsoringRateLimit {382	SponsoringDisabled,383	Blocks(u32),384}385386/// BoundedVec doesn't supports serde387#[cfg(feature = "serde1")]388mod bounded_serde {389	use core::convert::TryFrom;390	use frame_support::{BoundedVec, traits::Get};391	use serde::{392		ser::{self, Serialize},393		de::{self, Deserialize, Error},394	};395	use sp_std::vec::Vec;396397	pub fn serialize<D, V, S>(value: &BoundedVec<V, S>, serializer: D) -> Result<D::Ok, D::Error>398	where399		D: ser::Serializer,400		V: Serialize,401	{402		(value as &Vec<_>).serialize(serializer)403	}404405	pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>406	where407		D: de::Deserializer<'de>,408		V: de::Deserialize<'de>,409		S: Get<u32>,410	{411		// TODO: Implement custom visitor, which will limit vec size at parse time? Will serde only be used by chainspec?412		let vec = <Vec<V>>::deserialize(deserializer)?;413		let len = vec.len();414		TryFrom::try_from(vec).map_err(|_| D::Error::invalid_length(len, &"lesser size"))415	}416}417418fn bounded_debug<V, S>(v: &BoundedVec<V, S>, f: &mut fmt::Formatter) -> Result<(), fmt::Error>419where420	V: fmt::Debug,421{422	use core::fmt::Debug;423	(&v as &Vec<V>).fmt(f)424}425426#[cfg(feature = "serde1")]427#[allow(dead_code)]428mod bounded_map_serde {429	use core::convert::TryFrom;430	use sp_std::collections::btree_map::BTreeMap;431	use frame_support::{traits::Get, storage::bounded_btree_map::BoundedBTreeMap};432	use serde::{433		ser::{self, Serialize},434		de::{self, Deserialize, Error},435	};436	pub fn serialize<D, K, V, S>(437		value: &BoundedBTreeMap<K, V, S>,438		serializer: D,439	) -> Result<D::Ok, D::Error>440	where441		D: ser::Serializer,442		K: Serialize + Ord,443		V: Serialize,444	{445		(value as &BTreeMap<_, _>).serialize(serializer)446	}447448	pub fn deserialize<'de, D, K, V, S>(449		deserializer: D,450	) -> Result<BoundedBTreeMap<K, V, S>, D::Error>451	where452		D: de::Deserializer<'de>,453		K: de::Deserialize<'de> + Ord,454		V: de::Deserialize<'de>,455		S: Get<u32>,456	{457		let map = <BTreeMap<K, V>>::deserialize(deserializer)?;458		let len = map.len();459		TryFrom::try_from(map).map_err(|_| D::Error::invalid_length(len, &"lesser size"))460	}461}462463fn bounded_map_debug<K, V, S>(464	v: &BoundedBTreeMap<K, V, S>,465	f: &mut fmt::Formatter,466) -> Result<(), fmt::Error>467where468	K: fmt::Debug + Ord,469	V: fmt::Debug,470{471	use core::fmt::Debug;472	(&v as &BTreeMap<K, V>).fmt(f)473}474475#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]476#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]477#[derivative(Debug)]478pub struct CreateNftData {479	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]480	#[derivative(Debug(format_with = "bounded_debug"))]481	pub const_data: BoundedVec<u8, CustomDataLimit>,482	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]483	#[derivative(Debug(format_with = "bounded_debug"))]484	pub variable_data: BoundedVec<u8, CustomDataLimit>,485}486487#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]488#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]489pub struct CreateFungibleData {490	pub value: u128,491}492493#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]494#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]495#[derivative(Debug)]496pub struct CreateReFungibleData {497	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]498	#[derivative(Debug(format_with = "bounded_debug"))]499	pub const_data: BoundedVec<u8, CustomDataLimit>,500	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]501	#[derivative(Debug(format_with = "bounded_debug"))]502	pub variable_data: BoundedVec<u8, CustomDataLimit>,503	pub pieces: u128,504}505506#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]507#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]508pub enum MetaUpdatePermission {509	ItemOwner,510	Admin,511	None,512}513514impl Default for MetaUpdatePermission {515	fn default() -> Self {516		Self::ItemOwner517	}518}519520#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]521#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]522pub enum CreateItemData {523	NFT(CreateNftData),524	Fungible(CreateFungibleData),525	ReFungible(CreateReFungibleData),526}527528impl CreateItemData {529	pub fn data_size(&self) -> usize {530		match self {531			CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),532			CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),533			_ => 0,534		}535	}536}537538impl From<CreateNftData> for CreateItemData {539	fn from(item: CreateNftData) -> Self {540		CreateItemData::NFT(item)541	}542}543544impl From<CreateReFungibleData> for CreateItemData {545	fn from(item: CreateReFungibleData) -> Self {546		CreateItemData::ReFungible(item)547	}548}549550impl From<CreateFungibleData> for CreateItemData {551	fn from(item: CreateFungibleData) -> Self {552		CreateItemData::Fungible(item)553	}554}555556#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]557#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]558pub struct CollectionStats {559	pub created: u32,560	pub destroyed: u32,561	pub alive: u32,562}