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;2930pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;31pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;32pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;3334pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {35 100_00036} else {37 1038};39pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {40 100_00041} else {42 1043};44pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {45 204846} else {47 1048};49pub const COLLECTION_ADMINS_LIMIT: u32 = 5;50pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;51pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {52 1_000_00053} else {54 1055};565758pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;59pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;60pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;6162pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;636465pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;66pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;67pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 1048576;6869pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;70pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;71pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;72737475pub const MAX_ITEMS_PER_BATCH: u32 = 200;7677parameter_types! {78 pub const CustomDataLimit: u32 = CUSTOM_DATA_LIMIT;79}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 156 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 209 Disabled,210 Unconfirmed(AccountId),211 212 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, 259 #[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, Debug, Clone, PartialEq, TypeInfo)]267#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]268pub struct NftItemType<AccountId> {269 pub owner: AccountId,270 pub const_data: Vec<u8>,271 pub variable_data: Vec<u8>,272}273274#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]275#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]276pub struct FungibleItemType {277 pub value: u128,278}279280#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]281#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]282pub struct ReFungibleItemType<AccountId> {283 pub owner: Vec<Ownership<AccountId>>,284 pub const_data: Vec<u8>,285 pub variable_data: Vec<u8>,286}287288289#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]290#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]291pub struct CollectionLimits {292 pub account_token_ownership_limit: Option<u32>,293 pub sponsored_data_size: Option<u32>,294 295 296 297 pub sponsored_data_rate_limit: Option<(Option<u32>,)>,298 pub token_limit: Option<u32>,299300 301 pub sponsor_transfer_timeout: Option<u32>,302 pub sponsor_approve_timeout: Option<u32>,303 pub owner_can_transfer: Option<bool>,304 pub owner_can_destroy: Option<bool>,305 pub transfers_enabled: Option<bool>,306}307308impl CollectionLimits {309 pub fn account_token_ownership_limit(&self) -> u32 {310 self.account_token_ownership_limit311 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)312 .min(MAX_TOKEN_OWNERSHIP)313 }314 pub fn sponsored_data_size(&self) -> u32 {315 self.sponsored_data_size316 .unwrap_or(CUSTOM_DATA_LIMIT)317 .min(CUSTOM_DATA_LIMIT)318 }319 pub fn token_limit(&self) -> u32 {320 self.token_limit321 .unwrap_or(COLLECTION_TOKEN_LIMIT)322 .min(COLLECTION_TOKEN_LIMIT)323 }324 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {325 self.sponsor_transfer_timeout326 .unwrap_or(default)327 .min(MAX_SPONSOR_TIMEOUT)328 }329 pub fn sponsor_approve_timeout(&self) -> u32 {330 self.sponsor_approve_timeout331 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)332 .min(MAX_SPONSOR_TIMEOUT)333 }334 pub fn owner_can_transfer(&self) -> bool {335 self.owner_can_transfer.unwrap_or(true)336 }337 pub fn owner_can_destroy(&self) -> bool {338 self.owner_can_destroy.unwrap_or(true)339 }340 pub fn transfers_enabled(&self) -> bool {341 self.transfers_enabled.unwrap_or(true)342 }343 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {344 self.sponsored_data_rate_limit345 .unwrap_or((None,))346 .0347 .map(|v| v.min(MAX_SPONSOR_TIMEOUT))348 }349}350351352#[cfg(feature = "serde1")]353mod bounded_serde {354 use core::convert::TryFrom;355 use frame_support::{BoundedVec, traits::Get};356 use serde::{357 ser::{self, Serialize},358 de::{self, Deserialize, Error},359 };360 use sp_std::vec::Vec;361362 pub fn serialize<D, V, S>(value: &BoundedVec<V, S>, serializer: D) -> Result<D::Ok, D::Error>363 where364 D: ser::Serializer,365 V: Serialize,366 {367 (value as &Vec<_>).serialize(serializer)368 }369370 pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>371 where372 D: de::Deserializer<'de>,373 V: de::Deserialize<'de>,374 S: Get<u32>,375 {376 377 let vec = <Vec<V>>::deserialize(deserializer)?;378 let len = vec.len();379 TryFrom::try_from(vec).map_err(|_| D::Error::invalid_length(len, &"lesser size"))380 }381}382383#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]384#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]385#[derivative(Debug)]386pub struct CreateNftData {387 #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]388 #[derivative(Debug = "ignore")]389 pub const_data: BoundedVec<u8, CustomDataLimit>,390 #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]391 #[derivative(Debug = "ignore")]392 pub variable_data: BoundedVec<u8, CustomDataLimit>,393}394395#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]396#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]397pub struct CreateFungibleData {398 pub value: u128,399}400401#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]402#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]403#[derivative(Debug)]404pub struct CreateReFungibleData {405 #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]406 #[derivative(Debug = "ignore")]407 pub const_data: BoundedVec<u8, CustomDataLimit>,408 #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]409 #[derivative(Debug = "ignore")]410 pub variable_data: BoundedVec<u8, CustomDataLimit>,411 pub pieces: u128,412}413414#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]415#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]416pub enum MetaUpdatePermission {417 ItemOwner,418 Admin,419 None,420}421422impl Default for MetaUpdatePermission {423 fn default() -> Self {424 Self::ItemOwner425 }426}427428#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]429#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]430pub enum CreateItemData {431 NFT(CreateNftData),432 Fungible(CreateFungibleData),433 ReFungible(CreateReFungibleData),434}435436impl CreateItemData {437 pub fn data_size(&self) -> usize {438 match self {439 CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),440 CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),441 _ => 0,442 }443 }444}445446impl From<CreateNftData> for CreateItemData {447 fn from(item: CreateNftData) -> Self {448 CreateItemData::NFT(item)449 }450}451452impl From<CreateReFungibleData> for CreateItemData {453 fn from(item: CreateReFungibleData) -> Self {454 CreateItemData::ReFungible(item)455 }456}457458impl From<CreateFungibleData> for CreateItemData {459 fn from(item: CreateFungibleData) -> Self {460 CreateItemData::Fungible(item)461 }462}463464#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]465#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]466pub struct CollectionStats {467 pub created: u32,468 pub destroyed: u32,469 pub alive: u32,470}