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, Clone, PartialEq, TypeInfo, Debug, Derivative, MaxEncodedLen)]267#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]268#[derivative(Default)]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}312313314#[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 320 321 322 pub sponsored_data_rate_limit: Option<(Option<u32>,)>,323 pub token_limit: Option<u32>,324325 326 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 self.sponsored_data_rate_limit370 .unwrap_or((None,))371 .0372 .map(|v| v.min(MAX_SPONSOR_TIMEOUT))373 }374}375376377#[cfg(feature = "serde1")]378mod bounded_serde {379 use core::convert::TryFrom;380 use frame_support::{BoundedVec, traits::Get};381 use serde::{382 ser::{self, Serialize},383 de::{self, Deserialize, Error},384 };385 use sp_std::vec::Vec;386387 pub fn serialize<D, V, S>(value: &BoundedVec<V, S>, serializer: D) -> Result<D::Ok, D::Error>388 where389 D: ser::Serializer,390 V: Serialize,391 {392 (value as &Vec<_>).serialize(serializer)393 }394395 pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>396 where397 D: de::Deserializer<'de>,398 V: de::Deserialize<'de>,399 S: Get<u32>,400 {401 402 let vec = <Vec<V>>::deserialize(deserializer)?;403 let len = vec.len();404 TryFrom::try_from(vec).map_err(|_| D::Error::invalid_length(len, &"lesser size"))405 }406}407408#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]409#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]410#[derivative(Debug)]411pub struct CreateNftData {412 #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]413 #[derivative(Debug = "ignore")]414 pub const_data: BoundedVec<u8, CustomDataLimit>,415 #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]416 #[derivative(Debug = "ignore")]417 pub variable_data: BoundedVec<u8, CustomDataLimit>,418}419420#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]421#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]422pub struct CreateFungibleData {423 pub value: u128,424}425426#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]427#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]428#[derivative(Debug)]429pub struct CreateReFungibleData {430 #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]431 #[derivative(Debug = "ignore")]432 pub const_data: BoundedVec<u8, CustomDataLimit>,433 #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]434 #[derivative(Debug = "ignore")]435 pub variable_data: BoundedVec<u8, CustomDataLimit>,436 pub pieces: u128,437}438439#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]440#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]441pub enum MetaUpdatePermission {442 ItemOwner,443 Admin,444 None,445}446447impl Default for MetaUpdatePermission {448 fn default() -> Self {449 Self::ItemOwner450 }451}452453#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]454#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]455pub enum CreateItemData {456 NFT(CreateNftData),457 Fungible(CreateFungibleData),458 ReFungible(CreateReFungibleData),459}460461impl CreateItemData {462 pub fn data_size(&self) -> usize {463 match self {464 CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),465 CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),466 _ => 0,467 }468 }469}470471impl From<CreateNftData> for CreateItemData {472 fn from(item: CreateNftData) -> Self {473 CreateItemData::NFT(item)474 }475}476477impl From<CreateReFungibleData> for CreateItemData {478 fn from(item: CreateReFungibleData) -> Self {479 CreateItemData::ReFungible(item)480 }481}482483impl From<CreateFungibleData> for CreateItemData {484 fn from(item: CreateFungibleData) -> Self {485 CreateItemData::Fungible(item)486 }487}488489#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]490#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]491pub struct CollectionStats {492 pub created: u32,493 pub destroyed: u32,494 pub alive: u32,495}