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;3233pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {34 10_000_00035} else {36 1037};38pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {39 100_00040} else {41 1042};43pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {44 204845} else {46 1047};48pub const COLLECTION_ADMINS_LIMIT: u32 = 5;49pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;50pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {51 1_000_00052} else {53 1054};555657pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;58pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;59pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;6061pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;626364pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 1024;65pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 1024;66pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 1024;6768pub const MAX_COLLECTION_NAME_LENGTH: usize = 64;69pub const MAX_COLLECTION_DESCRIPTION_LENGTH: usize = 256;70pub const MAX_TOKEN_PREFIX_LENGTH: usize = 16;71727374pub const MAX_ITEMS_PER_BATCH: u32 = 200;7576parameter_types! {77 pub const CustomDataLimit: u32 = CUSTOM_DATA_LIMIT;78}7980#[derive(Encode, Decode, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default, TypeInfo)]81#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]82pub struct CollectionId(pub u32);83impl EncodeLike<u32> for CollectionId {}84impl EncodeLike<CollectionId> for u32 {}8586#[derive(Encode, Decode, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default, TypeInfo)]87#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]88pub struct TokenId(pub u32);89impl EncodeLike<u32> for TokenId {}90impl EncodeLike<TokenId> for u32 {}9192impl TokenId {93 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {94 self.095 .checked_add(1)96 .ok_or(ArithmeticError::Overflow)97 .map(Self)98 }99}100101impl From<TokenId> for U256 {102 fn from(t: TokenId) -> Self {103 t.0.into()104 }105}106107impl TryFrom<U256> for TokenId {108 type Error = &'static str;109110 fn try_from(value: U256) -> Result<Self, Self::Error> {111 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))112 }113}114115pub struct OverflowError;116impl From<OverflowError> for &'static str {117 fn from(_: OverflowError) -> Self {118 "overflow occured"119 }120}121122pub type DecimalPoints = u8;123124#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo)]125#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]126pub enum CollectionMode {127 NFT,128 129 Fungible(DecimalPoints),130 ReFungible,131}132133impl CollectionMode {134 pub fn id(&self) -> u8 {135 match self {136 CollectionMode::NFT => 1,137 CollectionMode::Fungible(_) => 2,138 CollectionMode::ReFungible => 3,139 }140 }141}142143pub trait SponsoringResolve<AccountId, Call> {144 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;145}146147#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo)]148#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]149pub enum AccessMode {150 Normal,151 AllowList,152}153impl Default for AccessMode {154 fn default() -> Self {155 Self::Normal156 }157}158159#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo)]160#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]161pub enum SchemaVersion {162 ImageURL,163 Unique,164}165impl Default for SchemaVersion {166 fn default() -> Self {167 Self::ImageURL168 }169}170171#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]172#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]173pub struct Ownership<AccountId> {174 pub owner: AccountId,175 pub fraction: u128,176}177178#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]179#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]180pub enum SponsorshipState<AccountId> {181 182 Disabled,183 Unconfirmed(AccountId),184 185 Confirmed(AccountId),186}187188impl<AccountId> SponsorshipState<AccountId> {189 pub fn sponsor(&self) -> Option<&AccountId> {190 match self {191 Self::Confirmed(sponsor) => Some(sponsor),192 _ => None,193 }194 }195196 pub fn pending_sponsor(&self) -> Option<&AccountId> {197 match self {198 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),199 _ => None,200 }201 }202203 pub fn confirmed(&self) -> bool {204 matches!(self, Self::Confirmed(_))205 }206}207208impl<T> Default for SponsorshipState<T> {209 fn default() -> Self {210 Self::Disabled211 }212}213214#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]215#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]216pub struct Collection<AccountId> {217 pub owner: AccountId,218 pub mode: CollectionMode,219 pub access: AccessMode,220 pub name: Vec<u16>, 221 pub description: Vec<u16>, 222 pub token_prefix: Vec<u8>, 223 pub mint_mode: bool,224 pub offchain_schema: Vec<u8>,225 pub schema_version: SchemaVersion,226 pub sponsorship: SponsorshipState<AccountId>,227 pub limits: CollectionLimits, 228 pub variable_on_chain_schema: Vec<u8>, 229 pub const_on_chain_schema: Vec<u8>, 230 pub meta_update_permission: MetaUpdatePermission,231}232233#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]234#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]235pub struct NftItemType<AccountId> {236 pub owner: AccountId,237 pub const_data: Vec<u8>,238 pub variable_data: Vec<u8>,239}240241#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]242#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]243pub struct FungibleItemType {244 pub value: u128,245}246247#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]248#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]249pub struct ReFungibleItemType<AccountId> {250 pub owner: Vec<Ownership<AccountId>>,251 pub const_data: Vec<u8>,252 pub variable_data: Vec<u8>,253}254255256#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo)]257#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]258pub struct CollectionLimits {259 pub account_token_ownership_limit: Option<u32>,260 pub sponsored_data_size: Option<u32>,261 262 263 264 pub sponsored_data_rate_limit: Option<(Option<u32>,)>,265 pub token_limit: Option<u32>,266267 268 pub sponsor_transfer_timeout: Option<u32>,269 pub sponsor_approve_timeout: Option<u32>,270 pub owner_can_transfer: Option<bool>,271 pub owner_can_destroy: Option<bool>,272 pub transfers_enabled: Option<bool>,273}274275impl CollectionLimits {276 pub fn account_token_ownership_limit(&self) -> u32 {277 self.account_token_ownership_limit278 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)279 .min(MAX_TOKEN_OWNERSHIP)280 }281 pub fn sponsored_data_size(&self) -> u32 {282 self.sponsored_data_size283 .unwrap_or(CUSTOM_DATA_LIMIT)284 .min(CUSTOM_DATA_LIMIT)285 }286 pub fn token_limit(&self) -> u32 {287 self.token_limit288 .unwrap_or(COLLECTION_TOKEN_LIMIT)289 .min(COLLECTION_TOKEN_LIMIT)290 }291 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {292 self.sponsor_transfer_timeout293 .unwrap_or(default)294 .min(MAX_SPONSOR_TIMEOUT)295 }296 pub fn sponsor_approve_timeout(&self) -> u32 {297 self.sponsor_approve_timeout298 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)299 .min(MAX_SPONSOR_TIMEOUT)300 }301 pub fn owner_can_transfer(&self) -> bool {302 self.owner_can_transfer.unwrap_or(true)303 }304 pub fn owner_can_destroy(&self) -> bool {305 self.owner_can_destroy.unwrap_or(true)306 }307 pub fn transfers_enabled(&self) -> bool {308 self.transfers_enabled.unwrap_or(true)309 }310 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {311 self.sponsored_data_rate_limit312 .unwrap_or((None,))313 .0314 .map(|v| v.min(MAX_SPONSOR_TIMEOUT))315 }316}317318319#[cfg(feature = "serde1")]320mod bounded_serde {321 use core::convert::TryFrom;322 use frame_support::{BoundedVec, traits::Get};323 use serde::{324 ser::{self, Serialize},325 de::{self, Deserialize, Error},326 };327 use sp_std::vec::Vec;328329 pub fn serialize<D, V, S>(value: &BoundedVec<V, S>, serializer: D) -> Result<D::Ok, D::Error>330 where331 D: ser::Serializer,332 V: Serialize,333 {334 let vec: &Vec<_> = &value;335 vec.serialize(serializer)336 }337338 pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>339 where340 D: de::Deserializer<'de>,341 V: de::Deserialize<'de>,342 S: Get<u32>,343 {344 345 let vec = <Vec<V>>::deserialize(deserializer)?;346 let len = vec.len();347 TryFrom::try_from(vec).map_err(|_| D::Error::invalid_length(len, &"lesser size"))348 }349}350351#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]352#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]353#[derivative(Debug)]354pub struct CreateNftData {355 #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]356 #[derivative(Debug = "ignore")]357 pub const_data: BoundedVec<u8, CustomDataLimit>,358 #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]359 #[derivative(Debug = "ignore")]360 pub variable_data: BoundedVec<u8, CustomDataLimit>,361}362363#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]364#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]365pub struct CreateFungibleData {366 pub value: u128,367}368369#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]370#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]371#[derivative(Debug)]372pub struct CreateReFungibleData {373 #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]374 #[derivative(Debug = "ignore")]375 pub const_data: BoundedVec<u8, CustomDataLimit>,376 #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]377 #[derivative(Debug = "ignore")]378 pub variable_data: BoundedVec<u8, CustomDataLimit>,379 pub pieces: u128,380}381382#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]383#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]384pub enum MetaUpdatePermission {385 ItemOwner,386 Admin,387 None,388}389390impl Default for MetaUpdatePermission {391 fn default() -> Self {392 Self::ItemOwner393 }394}395396#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]397#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]398pub enum CreateItemData {399 NFT(CreateNftData),400 Fungible(CreateFungibleData),401 ReFungible(CreateReFungibleData),402}403404impl CreateItemData {405 pub fn data_size(&self) -> usize {406 match self {407 CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),408 CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),409 _ => 0,410 }411 }412}413414impl From<CreateNftData> for CreateItemData {415 fn from(item: CreateNftData) -> Self {416 CreateItemData::NFT(item)417 }418}419420impl From<CreateReFungibleData> for CreateItemData {421 fn from(item: CreateReFungibleData) -> Self {422 CreateItemData::ReFungible(item)423 }424}425426impl From<CreateFungibleData> for CreateItemData {427 fn from(item: CreateFungibleData) -> Self {428 CreateItemData::Fungible(item)429 }430}431432#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]433#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]434pub struct CollectionStats {435 pub created: u32,436 pub destroyed: u32,437 pub alive: u32,438}