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

difftreelog

source

primitives/nft/src/lib.rs12.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};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;32pub const MAX_TOKEN_OWNERSHIP: u32 = 10_000_000;3334pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {35	10000036} else {37	1038};39pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {40	204841} else {42	1043};44pub const COLLECTION_ADMINS_LIMIT: u32 = 5;45pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;46pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {47	100000048} else {49	1050};5152// Timeouts for item types in passed blocks53pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;54pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;55pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;5657pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;5859// Schema limits60pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 1024;61pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 1024;62pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 1024;6364pub const MAX_COLLECTION_NAME_LENGTH: usize = 64;65pub const MAX_COLLECTION_DESCRIPTION_LENGTH: usize = 256;66pub const MAX_TOKEN_PREFIX_LENGTH: usize = 16;6768/// How much items can be created per single69/// create_many call70pub const MAX_ITEMS_PER_BATCH: u32 = 200;7172parameter_types! {73	pub const CustomDataLimit: u32 = CUSTOM_DATA_LIMIT;74}7576#[derive(Encode, Decode, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default, TypeInfo)]77#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]78pub struct CollectionId(pub u32);79impl EncodeLike<u32> for CollectionId {}80impl EncodeLike<CollectionId> for u32 {}8182#[derive(Encode, Decode, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default, TypeInfo)]83#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]84pub struct TokenId(pub u32);85impl EncodeLike<u32> for TokenId {}86impl EncodeLike<TokenId> for u32 {}8788impl TokenId {89	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {90		self.091			.checked_add(1)92			.ok_or(ArithmeticError::Overflow)93			.map(Self)94	}95}9697impl From<TokenId> for U256 {98	fn from(t: TokenId) -> Self {99		t.0.into()100	}101}102103impl TryFrom<U256> for TokenId {104	type Error = &'static str;105106	fn try_from(value: U256) -> Result<Self, Self::Error> {107		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))108	}109}110111pub struct OverflowError;112impl From<OverflowError> for &'static str {113	fn from(_: OverflowError) -> Self {114		"overflow occured"115	}116}117118pub type DecimalPoints = u8;119120#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo)]121#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]122pub enum CollectionMode {123	NFT,124	// decimal points125	Fungible(DecimalPoints),126	ReFungible,127}128129impl CollectionMode {130	pub fn id(&self) -> u8 {131		match self {132			CollectionMode::NFT => 1,133			CollectionMode::Fungible(_) => 2,134			CollectionMode::ReFungible => 3,135		}136	}137}138139pub trait SponsoringResolve<AccountId, Call> {140	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;141}142143#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo)]144#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]145pub enum AccessMode {146	Normal,147	AllowList,148}149impl Default for AccessMode {150	fn default() -> Self {151		Self::Normal152	}153}154155#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo)]156#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]157pub enum SchemaVersion {158	ImageURL,159	Unique,160}161impl Default for SchemaVersion {162	fn default() -> Self {163		Self::ImageURL164	}165}166167#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]168#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]169pub struct Ownership<AccountId> {170	pub owner: AccountId,171	pub fraction: u128,172}173174#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]175#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]176pub enum SponsorshipState<AccountId> {177	/// The fees are applied to the transaction sender178	Disabled,179	Unconfirmed(AccountId),180	/// Transactions are sponsored by specified account181	Confirmed(AccountId),182}183184impl<AccountId> SponsorshipState<AccountId> {185	pub fn sponsor(&self) -> Option<&AccountId> {186		match self {187			Self::Confirmed(sponsor) => Some(sponsor),188			_ => None,189		}190	}191192	pub fn pending_sponsor(&self) -> Option<&AccountId> {193		match self {194			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),195			_ => None,196		}197	}198199	pub fn confirmed(&self) -> bool {200		matches!(self, Self::Confirmed(_))201	}202}203204impl<T> Default for SponsorshipState<T> {205	fn default() -> Self {206		Self::Disabled207	}208}209210#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]211#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]212pub struct Collection<T: frame_system::Config> {213	pub owner: T::AccountId,214	pub mode: CollectionMode,215	pub access: AccessMode,216	pub name: Vec<u16>,        // 64 include null escape char217	pub description: Vec<u16>, // 256 include null escape char218	pub token_prefix: Vec<u8>, // 16 include null escape char219	pub mint_mode: bool,220	pub offchain_schema: Vec<u8>,221	pub schema_version: SchemaVersion,222	pub sponsorship: SponsorshipState<T::AccountId>,223	pub limits: CollectionLimits,          // Collection private restrictions224	pub variable_on_chain_schema: Vec<u8>, //225	pub const_on_chain_schema: Vec<u8>,    //226	pub meta_update_permission: MetaUpdatePermission,227}228229#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]230#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]231pub struct NftItemType<AccountId> {232	pub owner: AccountId,233	pub const_data: Vec<u8>,234	pub variable_data: Vec<u8>,235}236237#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]238#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]239pub struct FungibleItemType {240	pub value: u128,241}242243#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]244#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]245pub struct ReFungibleItemType<AccountId> {246	pub owner: Vec<Ownership<AccountId>>,247	pub const_data: Vec<u8>,248	pub variable_data: Vec<u8>,249}250251/// All fields are wrapped in `Option`s, where None means chain default252#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo)]253#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]254pub struct CollectionLimits {255	pub account_token_ownership_limit: Option<u32>,256	pub sponsored_data_size: Option<u32>,257	/// None - setVariableMetadata is not sponsored258	/// Some(v) - setVariableMetadata is sponsored259	///           if there is v block between txs260	pub sponsored_data_rate_limit: Option<(Option<u32>,)>,261	pub token_limit: Option<u32>,262263	// Timeouts for item types in passed blocks264	pub sponsor_transfer_timeout: Option<u32>,265	pub sponsor_approve_timeout: Option<u32>,266	pub owner_can_transfer: Option<bool>,267	pub owner_can_destroy: Option<bool>,268	pub transfers_enabled: Option<bool>,269}270271impl CollectionLimits {272	pub fn account_token_ownership_limit(&self) -> u32 {273		self.account_token_ownership_limit274			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)275			.min(MAX_TOKEN_OWNERSHIP)276	}277	pub fn sponsored_data_size(&self) -> u32 {278		self.sponsored_data_size279			.unwrap_or(CUSTOM_DATA_LIMIT)280			.min(CUSTOM_DATA_LIMIT)281	}282	pub fn token_limit(&self) -> u32 {283		self.token_limit284			.unwrap_or(COLLECTION_TOKEN_LIMIT)285			.min(COLLECTION_TOKEN_LIMIT)286	}287	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {288		self.sponsor_transfer_timeout289			.unwrap_or(default)290			.min(MAX_SPONSOR_TIMEOUT)291	}292	pub fn sponsor_approve_timeout(&self) -> u32 {293		self.sponsor_approve_timeout294			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)295			.min(MAX_SPONSOR_TIMEOUT)296	}297	pub fn owner_can_transfer(&self) -> bool {298		self.owner_can_transfer.unwrap_or(true)299	}300	pub fn owner_can_destroy(&self) -> bool {301		self.owner_can_destroy.unwrap_or(true)302	}303	pub fn transfers_enabled(&self) -> bool {304		self.transfers_enabled.unwrap_or(true)305	}306	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {307		self.sponsored_data_rate_limit308			.unwrap_or((None,))309			.0310			.map(|v| v.min(MAX_SPONSOR_TIMEOUT))311	}312}313314/// BoundedVec doesn't supports serde315#[cfg(feature = "serde1")]316mod bounded_serde {317	use core::convert::TryFrom;318	use frame_support::{BoundedVec, traits::Get};319	use serde::{320		ser::{self, Serialize},321		de::{self, Deserialize, Error},322	};323	use sp_std::vec::Vec;324325	pub fn serialize<D, V, S>(value: &BoundedVec<V, S>, serializer: D) -> Result<D::Ok, D::Error>326	where327		D: ser::Serializer,328		V: Serialize,329	{330		let vec: &Vec<_> = &value;331		vec.serialize(serializer)332	}333334	pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>335	where336		D: de::Deserializer<'de>,337		V: de::Deserialize<'de>,338		S: Get<u32>,339	{340		// TODO: Implement custom visitor, which will limit vec size at parse time? Will serde only be used by chainspec?341		let vec = <Vec<V>>::deserialize(deserializer)?;342		let len = vec.len();343		TryFrom::try_from(vec).map_err(|_| D::Error::invalid_length(len, &"lesser size"))344	}345}346347#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]348#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]349#[derivative(Debug)]350pub struct CreateNftData {351	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]352	#[derivative(Debug = "ignore")]353	pub const_data: BoundedVec<u8, CustomDataLimit>,354	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]355	#[derivative(Debug = "ignore")]356	pub variable_data: BoundedVec<u8, CustomDataLimit>,357}358359#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]360#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]361pub struct CreateFungibleData {362	pub value: u128,363}364365#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]366#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]367#[derivative(Debug)]368pub struct CreateReFungibleData {369	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]370	#[derivative(Debug = "ignore")]371	pub const_data: BoundedVec<u8, CustomDataLimit>,372	#[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]373	#[derivative(Debug = "ignore")]374	pub variable_data: BoundedVec<u8, CustomDataLimit>,375	pub pieces: u128,376}377378#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]379#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]380pub enum MetaUpdatePermission {381	ItemOwner,382	Admin,383	None,384}385386impl Default for MetaUpdatePermission {387	fn default() -> Self {388		Self::ItemOwner389	}390}391392#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]393#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]394pub enum CreateItemData {395	NFT(CreateNftData),396	Fungible(CreateFungibleData),397	ReFungible(CreateReFungibleData),398}399400impl CreateItemData {401	pub fn data_size(&self) -> usize {402		match self {403			CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),404			CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),405			_ => 0,406		}407	}408}409410impl From<CreateNftData> for CreateItemData {411	fn from(item: CreateNftData) -> Self {412		CreateItemData::NFT(item)413	}414}415416impl From<CreateReFungibleData> for CreateItemData {417	fn from(item: CreateReFungibleData) -> Self {418		CreateItemData::ReFungible(item)419	}420}421422impl From<CreateFungibleData> for CreateItemData {423	fn from(item: CreateFungibleData) -> Self {424		CreateItemData::Fungible(item)425	}426}