git.delta.rocks / unique-network / refs/commits / 1d12e73b766b

difftreelog

source

primitives/nft/src/lib.rs11.1 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;2728pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;29pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;30pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;31pub const MAX_TOKEN_OWNERSHIP: u32 = 10_000_000;3233pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {34	10000035} else {36	1037};38pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {39	204840} else {41	1042};43pub const COLLECTION_ADMINS_LIMIT: u64 = 5;44pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {45	100000046} else {47	1048};4950// Timeouts for item types in passed blocks51pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;52pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;53pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;5455// Schema limits56pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 1024;57pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 1024;58pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 1024;5960pub const MAX_COLLECTION_NAME_LENGTH: usize = 64;61pub const MAX_COLLECTION_DESCRIPTION_LENGTH: usize = 256;62pub const MAX_TOKEN_PREFIX_LENGTH: usize = 16;6364/// How much items can be created per single65/// create_many call66pub const MAX_ITEMS_PER_BATCH: u32 = 200;6768parameter_types! {69	pub const CustomDataLimit: u32 = CUSTOM_DATA_LIMIT;70}7172#[derive(Encode, Decode, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default)]73#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]74pub struct CollectionId(pub u32);75impl EncodeLike<u32> for CollectionId {}76impl EncodeLike<CollectionId> for u32 {}7778#[derive(Encode, Decode, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default)]79#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]80pub struct TokenId(pub u32);81impl EncodeLike<u32> for TokenId {}82impl EncodeLike<TokenId> for u32 {}8384impl TokenId {85	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {86		self.087			.checked_add(1)88			.ok_or(ArithmeticError::Overflow)89			.map(Self)90	}91}9293impl From<TokenId> for U256 {94	fn from(t: TokenId) -> Self {95		t.0.into()96	}97}9899impl TryFrom<U256> for TokenId {100	type Error = &'static str;101102	fn try_from(value: U256) -> Result<Self, Self::Error> {103		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))104	}105}106107pub struct OverflowError;108impl From<OverflowError> for &'static str {109	fn from(_: OverflowError) -> Self {110		"overflow occured"111	}112}113114pub type DecimalPoints = u8;115116#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]117#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]118pub enum CollectionMode {119	NFT,120	// decimal points121	Fungible(DecimalPoints),122	ReFungible,123}124125impl CollectionMode {126	pub fn id(&self) -> u8 {127		match self {128			CollectionMode::NFT => 1,129			CollectionMode::Fungible(_) => 2,130			CollectionMode::ReFungible => 3,131		}132	}133}134135pub trait SponsoringResolve<AccountId, Call> {136	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;137}138139#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]140#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]141pub enum AccessMode {142	Normal,143	WhiteList,144}145impl Default for AccessMode {146	fn default() -> Self {147		Self::Normal148	}149}150151#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]152#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]153pub enum SchemaVersion {154	ImageURL,155	Unique,156}157impl Default for SchemaVersion {158	fn default() -> Self {159		Self::ImageURL160	}161}162163#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]164#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]165pub struct Ownership<AccountId> {166	pub owner: AccountId,167	pub fraction: u128,168}169170#[derive(Encode, Decode, Debug, Clone, PartialEq)]171#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]172pub enum SponsorshipState<AccountId> {173	/// The fees are applied to the transaction sender174	Disabled,175	Unconfirmed(AccountId),176	/// Transactions are sponsored by specified account177	Confirmed(AccountId),178}179180impl<AccountId> SponsorshipState<AccountId> {181	pub fn sponsor(&self) -> Option<&AccountId> {182		match self {183			Self::Confirmed(sponsor) => Some(sponsor),184			_ => None,185		}186	}187188	pub fn pending_sponsor(&self) -> Option<&AccountId> {189		match self {190			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),191			_ => None,192		}193	}194195	pub fn confirmed(&self) -> bool {196		matches!(self, Self::Confirmed(_))197	}198}199200impl<T> Default for SponsorshipState<T> {201	fn default() -> Self {202		Self::Disabled203	}204}205206#[derive(Encode, Decode, Clone, PartialEq)]207#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]208pub struct Collection<T: frame_system::Config> {209	pub owner: T::AccountId,210	pub mode: CollectionMode,211	pub access: AccessMode,212	pub name: Vec<u16>,        // 64 include null escape char213	pub description: Vec<u16>, // 256 include null escape char214	pub token_prefix: Vec<u8>, // 16 include null escape char215	pub mint_mode: bool,216	pub offchain_schema: Vec<u8>,217	pub schema_version: SchemaVersion,218	pub sponsorship: SponsorshipState<T::AccountId>,219	pub limits: CollectionLimits<T::BlockNumber>, // Collection private restrictions220	pub variable_on_chain_schema: Vec<u8>,        //221	pub const_on_chain_schema: Vec<u8>,           //222	pub meta_update_permission: MetaUpdatePermission,223	pub transfers_enabled: bool,224}225226#[derive(Encode, Decode, Debug, Clone, PartialEq)]227#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]228pub struct NftItemType<AccountId> {229	pub owner: AccountId,230	pub const_data: Vec<u8>,231	pub variable_data: Vec<u8>,232}233234#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]235#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]236pub struct FungibleItemType {237	pub value: u128,238}239240#[derive(Encode, Decode, Debug, Clone, PartialEq)]241#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]242pub struct ReFungibleItemType<AccountId> {243	pub owner: Vec<Ownership<AccountId>>,244	pub const_data: Vec<u8>,245	pub variable_data: Vec<u8>,246}247248#[derive(Encode, Decode, Debug, Clone, PartialEq)]249#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]250pub struct CollectionLimits<BlockNumber: Encode + Decode> {251	pub account_token_ownership_limit: Option<u32>,252	pub sponsored_data_size: u32,253	/// None - setVariableMetadata is not sponsored254	/// Some(v) - setVariableMetadata is sponsored255	///           if there is v block between txs256	pub sponsored_data_rate_limit: Option<BlockNumber>,257	pub token_limit: u32,258259	// Timeouts for item types in passed blocks260	pub sponsor_transfer_timeout: u32,261	pub owner_can_transfer: bool,262	pub owner_can_destroy: bool,263}264265impl<BlockNumber: Encode + Decode> CollectionLimits<BlockNumber> {266	pub fn account_token_ownership_limit(&self) -> u32 {267		self.account_token_ownership_limit268			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)269			.min(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)270	}271}272273impl<BlockNumber: Encode + Decode> Default for CollectionLimits<BlockNumber> {274	fn default() -> Self {275		Self {276			account_token_ownership_limit: Some(10_000_000),277			token_limit: u32::max_value(),278			sponsored_data_size: u32::MAX,279			sponsored_data_rate_limit: None,280			sponsor_transfer_timeout: 14400,281			owner_can_transfer: true,282			owner_can_destroy: true,283		}284	}285}286287/// BoundedVec doesn't supports serde288#[cfg(feature = "serde1")]289mod bounded_serde {290	use core::convert::TryFrom;291	use frame_support::{BoundedVec, traits::Get};292	use serde::{293		ser::{self, Serialize},294		de::{self, Deserialize, Error},295	};296	use sp_std::vec::Vec;297298	pub fn serialize<D, V, S>(value: &BoundedVec<V, S>, serializer: D) -> Result<D::Ok, D::Error>299	where300		D: ser::Serializer,301		V: Serialize,302	{303		let vec: &Vec<_> = &value;304		vec.serialize(serializer)305	}306307	pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>308	where309		D: de::Deserializer<'de>,310		V: de::Deserialize<'de>,311		S: Get<u32>,312	{313		// TODO: Implement custom visitor, which will limit vec size at parse time? Will serde only be used by chainspec?314		let vec = <Vec<V>>::deserialize(deserializer)?;315		let len = vec.len();316		TryFrom::try_from(vec).map_err(|_| D::Error::invalid_length(len, &"lesser size"))317	}318}319320#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative)]321#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]322#[derivative(Debug)]323pub struct CreateNftData {324	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]325	#[derivative(Debug = "ignore")]326	pub const_data: BoundedVec<u8, CustomDataLimit>,327	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]328	#[derivative(Debug = "ignore")]329	pub variable_data: BoundedVec<u8, CustomDataLimit>,330}331332#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq)]333#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]334pub struct CreateFungibleData {335	pub value: u128,336}337338#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative)]339#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]340#[derivative(Debug)]341pub struct CreateReFungibleData {342	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]343	#[derivative(Debug = "ignore")]344	pub const_data: BoundedVec<u8, CustomDataLimit>,345	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]346	#[derivative(Debug = "ignore")]347	pub variable_data: BoundedVec<u8, CustomDataLimit>,348	pub pieces: u128,349}350351#[derive(Encode, Decode, Debug, Clone, PartialEq)]352#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]353pub enum MetaUpdatePermission {354	ItemOwner,355	Admin,356	None,357}358359impl Default for MetaUpdatePermission {360	fn default() -> Self {361		Self::ItemOwner362	}363}364365#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug)]366#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]367pub enum CreateItemData {368	NFT(CreateNftData),369	Fungible(CreateFungibleData),370	ReFungible(CreateReFungibleData),371}372373impl CreateItemData {374	pub fn data_size(&self) -> usize {375		match self {376			CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),377			CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),378			_ => 0,379		}380	}381}382383impl From<CreateNftData> for CreateItemData {384	fn from(item: CreateNftData) -> Self {385		CreateItemData::NFT(item)386	}387}388389impl From<CreateReFungibleData> for CreateItemData {390	fn from(item: CreateReFungibleData) -> Self {391		CreateItemData::ReFungible(item)392	}393}394395impl From<CreateFungibleData> for CreateItemData {396	fn from(item: CreateFungibleData) -> Self {397		CreateItemData::Fungible(item)398	}399}