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};515253pub 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;585960pub 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;67686970pub 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 125 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 178 Disabled,179 Unconfirmed(AccountId),180 181 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>, 217 pub description: Vec<u16>, 218 pub token_prefix: Vec<u8>, 219 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, 224 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#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo)]252#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]253pub struct CollectionLimits {254 pub account_token_ownership_limit: Option<u32>,255 pub sponsored_data_size: Option<u32>,256 257 258 259 pub sponsored_data_rate_limit: Option<u32>,260 pub token_limit: Option<u32>,261262 263 pub sponsor_transfer_timeout: Option<u32>,264 pub sponsor_approve_timeout: Option<u32>,265 pub owner_can_transfer: Option<bool>,266 pub owner_can_destroy: Option<bool>,267 pub transfers_enabled: Option<bool>,268}269270impl CollectionLimits {271 pub fn account_token_ownership_limit(&self) -> u32 {272 self.account_token_ownership_limit273 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)274 .min(MAX_TOKEN_OWNERSHIP)275 }276 pub fn sponsored_data_size(&self) -> u32 {277 self.sponsored_data_size278 .unwrap_or(CUSTOM_DATA_LIMIT)279 .min(CUSTOM_DATA_LIMIT)280 }281 pub fn token_limit(&self) -> u32 {282 self.token_limit283 .unwrap_or(COLLECTION_TOKEN_LIMIT)284 .min(COLLECTION_TOKEN_LIMIT)285 }286 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {287 self.sponsor_transfer_timeout288 .unwrap_or(default)289 .min(MAX_SPONSOR_TIMEOUT)290 }291 pub fn sponsor_approve_timeout(&self) -> u32 {292 self.sponsor_approve_timeout293 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)294 .min(MAX_SPONSOR_TIMEOUT)295 }296 pub fn owner_can_transfer(&self) -> bool {297 self.owner_can_transfer.unwrap_or(true)298 }299 pub fn owner_can_destroy(&self) -> bool {300 self.owner_can_destroy.unwrap_or(true)301 }302 pub fn transfers_enabled(&self) -> bool {303 self.transfers_enabled.unwrap_or(true)304 }305 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {306 self.sponsored_data_rate_limit307 .map(|v| v.min(MAX_SPONSOR_TIMEOUT))308 }309}310311312#[cfg(feature = "serde1")]313mod bounded_serde {314 use core::convert::TryFrom;315 use frame_support::{BoundedVec, traits::Get};316 use serde::{317 ser::{self, Serialize},318 de::{self, Deserialize, Error},319 };320 use sp_std::vec::Vec;321322 pub fn serialize<D, V, S>(value: &BoundedVec<V, S>, serializer: D) -> Result<D::Ok, D::Error>323 where324 D: ser::Serializer,325 V: Serialize,326 {327 let vec: &Vec<_> = &value;328 vec.serialize(serializer)329 }330331 pub fn deserialize<'de, D, V, S>(deserializer: D) -> Result<BoundedVec<V, S>, D::Error>332 where333 D: de::Deserializer<'de>,334 V: de::Deserialize<'de>,335 S: Get<u32>,336 {337 338 let vec = <Vec<V>>::deserialize(deserializer)?;339 let len = vec.len();340 TryFrom::try_from(vec).map_err(|_| D::Error::invalid_length(len, &"lesser size"))341 }342}343344#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]345#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]346#[derivative(Debug)]347pub struct CreateNftData {348 #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]349 #[derivative(Debug = "ignore")]350 pub const_data: BoundedVec<u8, CustomDataLimit>,351 #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]352 #[derivative(Debug = "ignore")]353 pub variable_data: BoundedVec<u8, CustomDataLimit>,354}355356#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]357#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]358pub struct CreateFungibleData {359 pub value: u128,360}361362#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]363#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]364#[derivative(Debug)]365pub struct CreateReFungibleData {366 #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]367 #[derivative(Debug = "ignore")]368 pub const_data: BoundedVec<u8, CustomDataLimit>,369 #[cfg_attr(feature = "serde1", serde(with = "bounded_serde"))]370 #[derivative(Debug = "ignore")]371 pub variable_data: BoundedVec<u8, CustomDataLimit>,372 pub pieces: u128,373}374375#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo)]376#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]377pub enum MetaUpdatePermission {378 ItemOwner,379 Admin,380 None,381}382383impl Default for MetaUpdatePermission {384 fn default() -> Self {385 Self::ItemOwner386 }387}388389#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]390#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]391pub enum CreateItemData {392 NFT(CreateNftData),393 Fungible(CreateFungibleData),394 ReFungible(CreateReFungibleData),395}396397impl CreateItemData {398 pub fn data_size(&self) -> usize {399 match self {400 CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),401 CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),402 _ => 0,403 }404 }405}406407impl From<CreateNftData> for CreateItemData {408 fn from(item: CreateNftData) -> Self {409 CreateItemData::NFT(item)410 }411}412413impl From<CreateReFungibleData> for CreateItemData {414 fn from(item: CreateReFungibleData) -> Self {415 CreateItemData::ReFungible(item)416 }417}418419impl From<CreateFungibleData> for CreateItemData {420 fn from(item: CreateFungibleData) -> Self {421 CreateItemData::Fungible(item)422 }423}