git.delta.rocks / unique-network / refs/commits / 73e422cd19aa

difftreelog

source

pallets/nft/src/lib.rs102.7 KiBsourcehistory
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56#![recursion_limit = "1024"]78#![cfg_attr(not(feature = "std"), no_std)]910#[cfg(feature = "std")]11pub use std::*;1213#[cfg(feature = "std")]14pub use serde::*;1516use core::ops::{Deref, DerefMut};17use codec::{Decode, Encode};18pub use frame_support::{19    construct_runtime, decl_event, decl_module, decl_storage, decl_error,20    dispatch::DispatchResult,21    ensure, fail, parameter_types,22    traits::{23        Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,24        Randomness, IsSubType,25    },26    weights::{27        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},28        DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,29        WeightToFeePolynomial, DispatchClass,30    },31    StorageValue,32};3334use frame_system::{self as system, ensure_signed, ensure_root};35use sp_runtime::sp_std::prelude::Vec;36use sp_runtime::{37    traits::{38        Hash, DispatchInfoOf, Dispatchable, PostDispatchInfoOf, Saturating, SaturatedConversion, SignedExtension, Zero,39    },40    transaction_validity::{41        TransactionPriority, InvalidTransaction, TransactionValidity, TransactionValidityError, ValidTransaction,42    },43    FixedPointOperand, FixedU128,44};45use sp_runtime::traits::StaticLookup;46use pallet_contracts::chain_extension::UncheckedFrom;47use pallet_transaction_payment::OnChargeTransaction;4849#[cfg(test)]50mod mock;5152#[cfg(test)]53mod tests;5455mod default_weights;5657pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;58pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;59pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;60pub const MAX_TOKEN_OWNERSHIP: u32 = 10_000_000;6162// Structs63// #region6465pub type CollectionId = u32;66pub type TokenId = u32;67pub type DecimalPoints = u8;6869#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]70#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]71pub enum CollectionMode {72    Invalid,73    NFT,74    // decimal points75    Fungible(DecimalPoints),76    ReFungible,77}7879impl Default for CollectionMode {80    fn default() -> Self {81        Self::Invalid82    }83}8485impl Into<u8> for CollectionMode {86    fn into(self) -> u8 {87        match self {88            CollectionMode::Invalid => 0,89            CollectionMode::NFT => 1,90            CollectionMode::Fungible(_) => 2,91            CollectionMode::ReFungible => 3,92        }93    }94}9596#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]97#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]98pub enum AccessMode {99    Normal,100    WhiteList,101}102impl Default for AccessMode {103    fn default() -> Self {104        Self::Normal105    }106}107108#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]109#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]110pub enum SchemaVersion {111    ImageURL,112    Unique,113}114impl Default for SchemaVersion {115    fn default() -> Self {116        Self::ImageURL117    }118}119120#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]121#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]122pub struct Ownership<AccountId> {123    pub owner: AccountId,124    pub fraction: u128,125}126127#[derive(Encode, Decode, Clone, PartialEq)]128#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]129pub struct Collection<T: Config> {130    pub owner: T::AccountId,131    pub mode: CollectionMode,132    pub access: AccessMode,133    pub decimal_points: DecimalPoints,134    pub name: Vec<u16>,        // 64 include null escape char135    pub description: Vec<u16>, // 256 include null escape char136    pub token_prefix: Vec<u8>, // 16 include null escape char137    pub mint_mode: bool,138    pub offchain_schema: Vec<u8>,139    pub schema_version: SchemaVersion,140    pub sponsor: T::AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender141    pub sponsor_confirmed: bool, // False if sponsor address has not yet confirmed sponsorship. True otherwise.142    pub limits: CollectionLimits<T::BlockNumber>, // Collection private restrictions 143    pub variable_on_chain_schema: Vec<u8>, //144    pub const_on_chain_schema: Vec<u8>, //145}146147pub struct CollectionHandle<T: Config> {148    pub id: CollectionId,149    collection: Collection<T>,150}151152impl<T: Config> Deref for CollectionHandle<T> {153    type Target = Collection<T>;154155    fn deref(&self) -> &Self::Target {156        &self.collection157    }158}159160impl<T: Config> DerefMut for CollectionHandle<T> {161    fn deref_mut(&mut self) -> &mut Self::Target {162        &mut self.collection163    }164}165166#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]167#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]168pub struct NftItemType<AccountId> {169    pub owner: AccountId,170    pub const_data: Vec<u8>,171    pub variable_data: Vec<u8>,172}173174#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]175#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]176pub struct FungibleItemType {177    pub value: u128,178}179180#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]181#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]182pub struct ReFungibleItemType<AccountId> {183    pub owner: Vec<Ownership<AccountId>>,184    pub const_data: Vec<u8>,185    pub variable_data: Vec<u8>,186}187188// #[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]189// #[cfg_attr(feature = "std", derive(Serialize, Deserialize))]190// pub struct VestingItem<AccountId, Moment> {191//     pub sender: AccountId,192//     pub recipient: AccountId,193//     pub collection_id: CollectionId,194//     pub item_id: TokenId,195//     pub amount: u64,196//     pub vesting_date: Moment,197// }198199#[derive(Encode, Decode, Debug, Clone, PartialEq)]200#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]201pub struct CollectionLimits<BlockNumber: Encode + Decode> {202    pub account_token_ownership_limit: u32,203    pub sponsored_data_size: u32,204    /// None - setVariableMetadata is not sponsored205    /// Some(v) - setVariableMetadata is sponsored 206    ///           if there is v block between txs207    pub sponsored_data_rate_limit: Option<BlockNumber>,208    pub token_limit: u32,209210    // Timeouts for item types in passed blocks211    pub sponsor_transfer_timeout: u32,212    pub owner_can_transfer: bool,213    pub owner_can_destroy: bool,214}215216impl<BlockNumber: Encode + Decode> Default for CollectionLimits<BlockNumber> {217    fn default() -> Self {218        Self { 219            account_token_ownership_limit: 10_000_000, 220            token_limit: u32::max_value(),221            sponsored_data_size: u32::MAX, 222            sponsored_data_rate_limit: None,223            sponsor_transfer_timeout: 14400,224            owner_can_transfer: true,225            owner_can_destroy: true226        }227    }228}229230#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]231#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]232pub struct ChainLimits {233    pub collection_numbers_limit: u32,234    pub account_token_ownership_limit: u32,235    pub collections_admins_limit: u64,236    pub custom_data_limit: u32,237238    // Timeouts for item types in passed blocks239    pub nft_sponsor_transfer_timeout: u32,240    pub fungible_sponsor_transfer_timeout: u32,241    pub refungible_sponsor_transfer_timeout: u32,242243    // Schema limits244    pub offchain_schema_limit: u32,245    pub variable_on_chain_schema_limit: u32,246    pub const_on_chain_schema_limit: u32,247}248249pub trait WeightInfo {250	fn create_collection() -> Weight;251	fn destroy_collection() -> Weight;252	fn add_to_white_list() -> Weight;253	fn remove_from_white_list() -> Weight;254    fn set_public_access_mode() -> Weight;255    fn set_mint_permission() -> Weight;256    fn change_collection_owner() -> Weight;257    fn add_collection_admin() -> Weight;258    fn remove_collection_admin() -> Weight;259    fn set_collection_sponsor() -> Weight;260    fn confirm_sponsorship() -> Weight;261    fn remove_collection_sponsor() -> Weight;262    fn create_item(s: usize) -> Weight;263    fn burn_item() -> Weight;264    fn transfer() -> Weight;265    fn approve() -> Weight;266    fn transfer_from() -> Weight;267    fn set_offchain_schema() -> Weight;268    fn set_const_on_chain_schema() -> Weight;269    fn set_variable_on_chain_schema() -> Weight;270    fn set_variable_meta_data() -> Weight;271    fn enable_contract_sponsoring() -> Weight;272    fn set_schema_version() -> Weight;273    fn set_chain_limits() -> Weight;274    fn set_contract_sponsoring_rate_limit() -> Weight;275    fn set_variable_meta_data_sponsoring_rate_limit() -> Weight;276    fn toggle_contract_white_list() -> Weight;277    fn add_to_contract_white_list() -> Weight;278    fn remove_from_contract_white_list() -> Weight;279    fn set_collection_limits() -> Weight;280}281282#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]283#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]284pub struct CreateNftData {285    pub const_data: Vec<u8>,286    pub variable_data: Vec<u8>,287}288289#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]290#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]291pub struct CreateFungibleData {292    pub value: u128,293}294295#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]296#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]297pub struct CreateReFungibleData {298    pub const_data: Vec<u8>,299    pub variable_data: Vec<u8>,300    pub pieces: u128,301}302303#[derive(Encode, Decode, Debug, Clone, PartialEq)]304#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]305pub enum CreateItemData {306    NFT(CreateNftData),307    Fungible(CreateFungibleData),308    ReFungible(CreateReFungibleData),309}310311impl CreateItemData {312    pub fn len(&self) -> usize {313        let len = match self {314            CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),315            CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),316            _ => 0317        };318        319        return len;320    }321}322323impl From<CreateNftData> for CreateItemData {324    fn from(item: CreateNftData) -> Self {325        CreateItemData::NFT(item)326    }327}328329impl From<CreateReFungibleData> for CreateItemData {330    fn from(item: CreateReFungibleData) -> Self {331        CreateItemData::ReFungible(item)332    }333}334335impl From<CreateFungibleData> for CreateItemData {336    fn from(item: CreateFungibleData) -> Self {337        CreateItemData::Fungible(item)338    }339}340341342decl_error! {343	/// Error for non-fungible-token module.344	pub enum Error for Module<T: Config> {345        /// Total collections bound exceeded.346        TotalCollectionsLimitExceeded,347		/// Decimal_points parameter must be lower than MAX_DECIMAL_POINTS constant, currently it is 30.348        CollectionDecimalPointLimitExceeded, 349        /// Collection name can not be longer than 63 char.350        CollectionNameLimitExceeded, 351        /// Collection description can not be longer than 255 char.352        CollectionDescriptionLimitExceeded, 353        /// Token prefix can not be longer than 15 char.354        CollectionTokenPrefixLimitExceeded,355        /// This collection does not exist.356        CollectionNotFound,357        /// Item not exists.358        TokenNotFound,359        /// Admin not found360        AdminNotFound,361        /// Arithmetic calculation overflow.362        NumOverflow,       363        /// Account already has admin role.364        AlreadyAdmin,  365        /// You do not own this collection.366        NoPermission,367        /// This address is not set as sponsor, use setCollectionSponsor first.368        ConfirmUnsetSponsorFail,369        /// Collection is not in mint mode.370        PublicMintingNotAllowed,371        /// Sender parameter and item owner must be equal.372        MustBeTokenOwner,373        /// Item balance not enough.374        TokenValueTooLow,375        /// Size of item is too large.376        NftSizeLimitExceeded,377        /// No approve found378        ApproveNotFound,379        /// Requested value more than approved.380        TokenValueNotEnough,381        /// Only approved addresses can call this method.382        ApproveRequired,383        /// Address is not in white list.384        AddresNotInWhiteList,385        /// Number of collection admins bound exceeded.386        CollectionAdminsLimitExceeded,387        /// Owned tokens by a single address bound exceeded.388        AddressOwnershipLimitExceeded,389        /// Length of items properties must be greater than 0.390        EmptyArgument,391        /// const_data exceeded data limit.392        TokenConstDataLimitExceeded,393        /// variable_data exceeded data limit.394        TokenVariableDataLimitExceeded,395        /// Not NFT item data used to mint in NFT collection.396        NotNftDataUsedToMintNftCollectionToken,397        /// Not Fungible item data used to mint in Fungible collection.398        NotFungibleDataUsedToMintFungibleCollectionToken,399        /// Not Re Fungible item data used to mint in Re Fungible collection.400        NotReFungibleDataUsedToMintReFungibleCollectionToken,401        /// Unexpected collection type.402        UnexpectedCollectionType,403        /// Can't store metadata in fungible tokens.404        CantStoreMetadataInFungibleTokens,405        /// Collection token limit exceeded406        CollectionTokenLimitExceeded,407        /// Account token limit exceeded per collection408        AccountTokenLimitExceeded,409        /// Collection limit bounds per collection exceeded410        CollectionLimitBoundsExceeded,411        /// Tried to enable permissions which are only permitted to be disabled412        OwnerPermissionsCantBeReverted,413        /// Schema data size limit bound exceeded414        SchemaDataLimitExceeded,415        /// Maximum refungibility exceeded416        WrongRefungiblePieces417	}418}419420pub trait Config: system::Config + Sized + pallet_transaction_payment::Config + pallet_contracts::Config {421    type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;422423    /// Weight information for extrinsics in this pallet.424	type WeightInfo: WeightInfo;425}426427#[cfg(feature = "runtime-benchmarks")]428mod benchmarking;429430// #endregion431432decl_storage! {433    trait Store for Module<T: Config> as Nft {434435        // Private members436        NextCollectionID: CollectionId;437        CreatedCollectionCount: u32;438        ChainVersion: u64;439        ItemListIndex: map hasher(identity) CollectionId => TokenId;440441        // Chain limits struct442        pub ChainLimit get(fn chain_limit) config(): ChainLimits;443444        // Bound counters445        CollectionCount: u32;446        pub AccountItemCount get(fn account_item_count): map hasher(twox_64_concat) T::AccountId => u32;447448        // Basic collections449        pub CollectionById get(fn collection_id) config(): map hasher(identity) CollectionId => Option<Collection<T>> = None;450        pub AdminList get(fn admin_list_collection): map hasher(identity) CollectionId => Vec<T::AccountId>;451        pub WhiteList get(fn white_list): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => bool;452453        /// Balance owner per collection map454        pub Balance get(fn balance_count): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => u128;455456        /// second parameter: item id + owner account id + spender account id457        pub Allowances get(fn approved): double_map hasher(identity) CollectionId, hasher(twox_64_concat) (TokenId, T::AccountId, T::AccountId) => u128;458459        /// Item collections460        pub NftItemList get(fn nft_item_id) config(): double_map hasher(identity) CollectionId, hasher(identity) TokenId => NftItemType<T::AccountId>;461        pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => FungibleItemType;462        pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(identity) CollectionId, hasher(identity) TokenId => ReFungibleItemType<T::AccountId>;463464        /// Index list465        pub AddressTokens get(fn address_tokens): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => Vec<TokenId>;466467        /// Tokens transfer baskets468        pub CreateItemBasket get(fn create_item_basket): map hasher(twox_64_concat) (CollectionId, T::AccountId) => T::BlockNumber;469        pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(identity) CollectionId, hasher(identity) TokenId => T::BlockNumber;470        pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(identity) CollectionId, hasher(twox_64_concat) T::AccountId => T::BlockNumber;471        pub ReFungibleTransferBasket get(fn refungible_transfer_basket): double_map hasher(identity) CollectionId, hasher(identity) TokenId => T::BlockNumber;472473        /// Variable metadata sponsoring474        pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(identity) CollectionId, hasher(identity) TokenId => Option<T::BlockNumber> = None;475476        // Contract Sponsorship and Ownership477        pub ContractOwner get(fn contract_owner): map hasher(twox_64_concat) T::AccountId => T::AccountId;478        pub ContractSelfSponsoring get(fn contract_self_sponsoring): map hasher(twox_64_concat) T::AccountId => bool;479        pub ContractSponsorBasket get(fn contract_sponsor_basket): map hasher(twox_64_concat) (T::AccountId, T::AccountId) => T::BlockNumber;480        pub ContractSponsoringRateLimit get(fn contract_sponsoring_rate_limit): map hasher(twox_64_concat) T::AccountId => T::BlockNumber;481        pub ContractWhiteListEnabled get(fn contract_white_list_enabled): map hasher(twox_64_concat) T::AccountId => bool; 482        pub ContractWhiteList get(fn contract_white_list): double_map hasher(twox_64_concat) T::AccountId, hasher(twox_64_concat) T::AccountId => bool; 483    }484    add_extra_genesis {485        build(|config: &GenesisConfig<T>| {486            // Modification of storage487            for (_num, _c) in &config.collection_id {488                <Module<T>>::init_collection(_c);489            }490491            for (_num, _c, _i) in &config.nft_item_id {492                <Module<T>>::init_nft_token(*_c, _i);493            }494495            for (collection_id, account_id, fungible_item) in &config.fungible_item_id {496                <Module<T>>::init_fungible_token(*collection_id, account_id, fungible_item);497            }498499            for (_num, _c, _i) in &config.refungible_item_id {500                <Module<T>>::init_refungible_token(*_c, _i);501            }502        })503    }504}505506decl_event!(507    pub enum Event<T>508    where509        AccountId = <T as system::Config>::AccountId,510    {511        /// New collection was created512        /// 513        /// # Arguments514        /// 515        /// * collection_id: Globally unique identifier of newly created collection.516        /// 517        /// * mode: [CollectionMode] converted into u8.518        /// 519        /// * account_id: Collection owner.520        Created(CollectionId, u8, AccountId),521522        /// New item was created.523        /// 524        /// # Arguments525        /// 526        /// * collection_id: Id of the collection where item was created.527        /// 528        /// * item_id: Id of an item. Unique within the collection.529        ///530        /// * recipient: Owner of newly created item 531        ItemCreated(CollectionId, TokenId, AccountId),532533        /// Collection item was burned.534        /// 535        /// # Arguments536        /// 537        /// collection_id.538        /// 539        /// item_id: Identifier of burned NFT.540        ItemDestroyed(CollectionId, TokenId),541542        /// Item was transferred543        ///544        /// * collection_id: Id of collection to which item is belong545        ///546        /// * item_id: Id of an item547        ///548        /// * sender: Original owner of item549        ///550        /// * recipient: New owner of item551        ///552        /// * amount: Always 1 for NFT553        Transfer(CollectionId, TokenId, AccountId, AccountId, u128),554    }555);556557decl_module! {558    pub struct Module<T: Config> for enum Call 559    where 560        origin: T::Origin561    {562        fn deposit_event() = default;563        type Error = Error<T>;564565        fn on_initialize(now: T::BlockNumber) -> Weight {566567            if ChainVersion::get() < 2568            {569                let value = NextCollectionID::get();570                CreatedCollectionCount::put(value);571                ChainVersion::put(2);572            }573574            0575        }576577        /// This method creates a Collection of NFTs. Each Token may have multiple properties encoded as an array of bytes of certain length. The initial owner and admin of the collection are set to the address that signed the transaction. Both addresses can be changed later.578        /// 579        /// # Permissions580        /// 581        /// * Anyone.582        /// 583        /// # Arguments584        /// 585        /// * collection_name: UTF-16 string with collection name (limit 64 characters), will be stored as zero-terminated.586        /// 587        /// * collection_description: UTF-16 string with collection description (limit 256 characters), will be stored as zero-terminated.588        /// 589        /// * token_prefix: UTF-8 string with token prefix.590        /// 591        /// * mode: [CollectionMode] collection type and type dependent data.592        // returns collection ID593        #[weight = <T as Config>::WeightInfo::create_collection()]594        pub fn create_collection(origin,595                                 collection_name: Vec<u16>,596                                 collection_description: Vec<u16>,597                                 token_prefix: Vec<u8>,598                                 mode: CollectionMode) -> DispatchResult {599600            // Anyone can create a collection601            let who = ensure_signed(origin)?;602603            let decimal_points = match mode {604                CollectionMode::Fungible(points) => points,605                _ => 0606            };607608            let chain_limit = ChainLimit::get();609610            // bound Total number of collections611            ensure!(CollectionCount::get() < chain_limit.collection_numbers_limit, Error::<T>::TotalCollectionsLimitExceeded);612613            // check params614            ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);615            ensure!(collection_name.len() <= 64, Error::<T>::CollectionNameLimitExceeded);616            ensure!(collection_description.len() <= 256, Error::<T>::CollectionDescriptionLimitExceeded);617            ensure!(token_prefix.len() <= 16, Error::<T>::CollectionTokenPrefixLimitExceeded);618619            // Generate next collection ID620            let next_id = CreatedCollectionCount::get()621                .checked_add(1)622                .ok_or(Error::<T>::NumOverflow)?;623624            // bound counter625            let total = CollectionCount::get()626                .checked_add(1)627                .ok_or(Error::<T>::NumOverflow)?;628629            CreatedCollectionCount::put(next_id);630            CollectionCount::put(total);631632            let limits = CollectionLimits {633                sponsored_data_size: chain_limit.custom_data_limit,634                ..Default::default()635            };636637            // Create new collection638            let new_collection = Collection {639                owner: who.clone(),640                name: collection_name,641                mode: mode.clone(),642                mint_mode: false,643                access: AccessMode::Normal,644                description: collection_description,645                decimal_points: decimal_points,646                token_prefix: token_prefix,647                offchain_schema: Vec::new(),648                schema_version: SchemaVersion::ImageURL,649                sponsor: T::AccountId::default(),650                sponsor_confirmed: false,651                variable_on_chain_schema: Vec::new(),652                const_on_chain_schema: Vec::new(),653                limits,654            };655656            // Add new collection to map657            <CollectionById<T>>::insert(next_id, new_collection);658659            // call event660            Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));661662            Ok(())663        }664665        /// **DANGEROUS**: Destroys collection and all NFTs within this collection. Users irrecoverably lose their assets and may lose real money.666        /// 667        /// # Permissions668        /// 669        /// * Collection Owner.670        /// 671        /// # Arguments672        /// 673        /// * collection_id: collection to destroy.674        #[weight = <T as Config>::WeightInfo::destroy_collection()]675        pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {676677            let sender = ensure_signed(origin)?;678            let collection = Self::get_collection(collection_id)?;679            Self::check_owner_permissions(&collection, sender)?;680            if !collection.limits.owner_can_destroy {681                fail!(Error::<T>::NoPermission);682            }683684            <AddressTokens<T>>::remove_prefix(collection_id);685            <Allowances<T>>::remove_prefix(collection_id);686            <Balance<T>>::remove_prefix(collection_id);687            <ItemListIndex>::remove(collection_id);688            <AdminList<T>>::remove(collection_id);689            <CollectionById<T>>::remove(collection_id);690            <WhiteList<T>>::remove_prefix(collection_id);691692            <NftItemList<T>>::remove_prefix(collection_id);693            <FungibleItemList<T>>::remove_prefix(collection_id);694            <ReFungibleItemList<T>>::remove_prefix(collection_id);695696            <NftTransferBasket<T>>::remove_prefix(collection_id);697            <FungibleTransferBasket<T>>::remove_prefix(collection_id);698            <ReFungibleTransferBasket<T>>::remove_prefix(collection_id);699700            <VariableMetaDataBasket<T>>::remove_prefix(collection_id);701702            if CollectionCount::get() > 0703            {704                // bound couter705                let total = CollectionCount::get()706                    .checked_sub(1)707                    .ok_or(Error::<T>::NumOverflow)?;708709                CollectionCount::put(total);710            }711712            Ok(())713        }714715        /// Add an address to white list.716        /// 717        /// # Permissions718        /// 719        /// * Collection Owner720        /// * Collection Admin721        /// 722        /// # Arguments723        /// 724        /// * collection_id.725        /// 726        /// * address.727        #[weight = <T as Config>::WeightInfo::add_to_white_list()]728        pub fn add_to_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{729730            let sender = ensure_signed(origin)?;731            let collection = Self::get_collection(collection_id)?;732            Self::check_owner_or_admin_permissions(&collection, sender)?;733734            <WhiteList<T>>::insert(collection_id, address, true);735            736            Ok(())737        }738739        /// Remove an address from white list.740        /// 741        /// # Permissions742        /// 743        /// * Collection Owner744        /// * Collection Admin745        /// 746        /// # Arguments747        /// 748        /// * collection_id.749        /// 750        /// * address.751        #[weight = <T as Config>::WeightInfo::remove_from_white_list()]752        pub fn remove_from_white_list(origin, collection_id: CollectionId, address: T::AccountId) -> DispatchResult{753754            let sender = ensure_signed(origin)?;755            let collection = Self::get_collection(collection_id)?;756            Self::check_owner_or_admin_permissions(&collection, sender)?;757758            <WhiteList<T>>::remove(collection_id, address);759760            Ok(())761        }762763        /// Toggle between normal and white list access for the methods with access for `Anyone`.764        /// 765        /// # Permissions766        /// 767        /// * Collection Owner.768        /// 769        /// # Arguments770        /// 771        /// * collection_id.772        /// 773        /// * mode: [AccessMode]774        #[weight = <T as Config>::WeightInfo::set_public_access_mode()]775        pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult776        {777            let sender = ensure_signed(origin)?;778779            let mut target_collection = Self::get_collection(collection_id)?;780            Self::check_owner_permissions(&target_collection, sender)?;781            target_collection.access = mode;782            Self::save_collection(target_collection);783784            Ok(())785        }786787        /// Allows Anyone to create tokens if:788        /// * White List is enabled, and789        /// * Address is added to white list, and790        /// * This method was called with True parameter791        /// 792        /// # Permissions793        /// * Collection Owner794        ///795        /// # Arguments796        /// 797        /// * collection_id.798        /// 799        /// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.800        #[weight = <T as Config>::WeightInfo::set_mint_permission()]801        pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult802        {803            let sender = ensure_signed(origin)?;804805            let mut target_collection = Self::get_collection(collection_id)?;806            Self::check_owner_permissions(&target_collection, sender)?;807            target_collection.mint_mode = mint_permission;808            Self::save_collection(target_collection);809810            Ok(())811        }812813        /// Change the owner of the collection.814        /// 815        /// # Permissions816        /// 817        /// * Collection Owner.818        /// 819        /// # Arguments820        /// 821        /// * collection_id.822        /// 823        /// * new_owner.824        #[weight = <T as Config>::WeightInfo::change_collection_owner()]825        pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {826827            let sender = ensure_signed(origin)?;828            let mut target_collection = Self::get_collection(collection_id)?;829            Self::check_owner_permissions(&target_collection, sender)?;830            target_collection.owner = new_owner;831            Self::save_collection(target_collection);832833            Ok(())834        }835836        /// Adds an admin of the Collection.837        /// NFT Collection can be controlled by multiple admin addresses (some which can also be servers, for example). Admins can issue and burn NFTs, as well as add and remove other admins, but cannot change NFT or Collection ownership. 838        /// 839        /// # Permissions840        /// 841        /// * Collection Owner.842        /// * Collection Admin.843        /// 844        /// # Arguments845        /// 846        /// * collection_id: ID of the Collection to add admin for.847        /// 848        /// * new_admin_id: Address of new admin to add.849        #[weight = <T as Config>::WeightInfo::add_collection_admin()]850        pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::AccountId) -> DispatchResult {851852            let sender = ensure_signed(origin)?;853            let collection = Self::get_collection(collection_id)?;854            Self::check_owner_or_admin_permissions(&collection, sender)?;855            let mut admin_arr: Vec<T::AccountId> = Vec::new();856857            if <AdminList<T>>::contains_key(collection_id)858            {859                admin_arr = <AdminList<T>>::get(collection_id);860                ensure!(!admin_arr.contains(&new_admin_id), Error::<T>::AlreadyAdmin);861            }862863            // Number of collection admins864            ensure!((admin_arr.len() as u64) < ChainLimit::get().collections_admins_limit, Error::<T>::CollectionAdminsLimitExceeded);865866            admin_arr.push(new_admin_id);867            <AdminList<T>>::insert(collection_id, admin_arr);868869            Ok(())870        }871872        /// Remove admin address of the Collection. An admin address can remove itself. List of admins may become empty, in which case only Collection Owner will be able to add an Admin.873        ///874        /// # Permissions875        /// 876        /// * Collection Owner.877        /// * Collection Admin.878        /// 879        /// # Arguments880        /// 881        /// * collection_id: ID of the Collection to remove admin for.882        /// 883        /// * account_id: Address of admin to remove.884        #[weight = <T as Config>::WeightInfo::remove_collection_admin()]885        pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::AccountId) -> DispatchResult {886887            let sender = ensure_signed(origin)?;888            let collection = Self::get_collection(collection_id)?;889            Self::check_owner_or_admin_permissions(&collection, sender)?;890            ensure!(<AdminList<T>>::contains_key(collection_id), Error::<T>::AdminNotFound);891892            let mut admin_arr = <AdminList<T>>::get(collection_id);893            admin_arr.retain(|i| *i != account_id);894            <AdminList<T>>::insert(collection_id, admin_arr);895896            Ok(())897        }898899        /// # Permissions900        /// 901        /// * Collection Owner902        /// 903        /// # Arguments904        /// 905        /// * collection_id.906        /// 907        /// * new_sponsor.908        #[weight = <T as Config>::WeightInfo::set_collection_sponsor()]909        pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {910911            let sender = ensure_signed(origin)?;912            let mut target_collection = Self::get_collection(collection_id)?;913            Self::check_owner_permissions(&target_collection, sender)?;914915            target_collection.sponsor = new_sponsor;916            target_collection.sponsor_confirmed = false;917            Self::save_collection(target_collection);918919            Ok(())920        }921922        /// # Permissions923        /// 924        /// * Sponsor.925        /// 926        /// # Arguments927        /// 928        /// * collection_id.929        #[weight = <T as Config>::WeightInfo::confirm_sponsorship()]930        pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {931932            let sender = ensure_signed(origin)?;933934            let mut target_collection = Self::get_collection(collection_id)?;935            ensure!(sender == target_collection.sponsor, Error::<T>::ConfirmUnsetSponsorFail);936937            target_collection.sponsor_confirmed = true;938            Self::save_collection(target_collection);939940            Ok(())941        }942943        /// Switch back to pay-per-own-transaction model.944        ///945        /// # Permissions946        ///947        /// * Collection owner.948        /// 949        /// # Arguments950        /// 951        /// * collection_id.952        #[weight = <T as Config>::WeightInfo::remove_collection_sponsor()]953        pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {954955            let sender = ensure_signed(origin)?;956957            let mut target_collection = Self::get_collection(collection_id)?;958            Self::check_owner_permissions(&target_collection, sender)?;959960            target_collection.sponsor = T::AccountId::default();961            target_collection.sponsor_confirmed = false;962            Self::save_collection(target_collection);963964            Ok(())965        }966967        /// This method creates a concrete instance of NFT Collection created with CreateCollection method.968        /// 969        /// # Permissions970        /// 971        /// * Collection Owner.972        /// * Collection Admin.973        /// * Anyone if974        ///     * White List is enabled, and975        ///     * Address is added to white list, and976        ///     * MintPermission is enabled (see SetMintPermission method)977        /// 978        /// # Arguments979        /// 980        /// * collection_id: ID of the collection.981        /// 982        /// * owner: Address, initial owner of the NFT.983        ///984        /// * data: Token data to store on chain.985        // #[weight =986        // (130_000_000 as Weight)987        // .saturating_add((2135 as Weight).saturating_mul((properties.len() as u64) as Weight))988        // .saturating_add(RocksDbWeight::get().reads(10 as Weight))989        // .saturating_add(RocksDbWeight::get().writes(8 as Weight))]990991        #[weight = <T as Config>::WeightInfo::create_item(data.len())]992        pub fn create_item(origin, collection_id: CollectionId, owner: T::AccountId, data: CreateItemData) -> DispatchResult {993994            let sender = ensure_signed(origin)?;995996            let target_collection = Self::get_collection(collection_id)?;997998            Self::can_create_items_in_collection(&target_collection, &sender, &owner)?;999            Self::validate_create_item_args(&target_collection, &data)?;1000            Self::create_item_no_validation(&target_collection, owner, data)?;10011002            Ok(())1003        }10041005        /// This method creates multiple instances of NFT Collection created with CreateCollection method.1006        /// 1007        /// # Permissions1008        /// 1009        /// * Collection Owner.1010        /// * Collection Admin.1011        /// * Anyone if1012        ///     * White List is enabled, and1013        ///     * Address is added to white list, and1014        ///     * MintPermission is enabled (see SetMintPermission method)1015        /// 1016        /// # Arguments1017        /// 1018        /// * collection_id: ID of the collection.1019        /// 1020        /// * itemsData: Array items properties. Each property is an array of bytes itself, see [create_item].1021        /// 1022        /// * owner: Address, initial owner of the NFT.1023        #[weight = <T as Config>::WeightInfo::create_item(items_data.into_iter()1024                               .map(|data| { data.len() })1025                               .sum())]1026        pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::AccountId, items_data: Vec<CreateItemData>) -> DispatchResult {10271028            ensure!(items_data.len() > 0, Error::<T>::EmptyArgument);1029            let sender = ensure_signed(origin)?;10301031            let target_collection = Self::get_collection(collection_id)?;10321033            Self::can_create_items_in_collection(&target_collection, &sender, &owner)?;10341035            for data in &items_data {1036                Self::validate_create_item_args(&target_collection, data)?;1037            }1038            for data in &items_data {1039                Self::create_item_no_validation(&target_collection, owner.clone(), data.clone())?;1040            }10411042            Ok(())1043        }10441045        /// Destroys a concrete instance of NFT.1046        /// 1047        /// # Permissions1048        /// 1049        /// * Collection Owner.1050        /// * Collection Admin.1051        /// * Current NFT Owner.1052        /// 1053        /// # Arguments1054        /// 1055        /// * collection_id: ID of the collection.1056        /// 1057        /// * item_id: ID of NFT to burn.1058        #[weight = <T as Config>::WeightInfo::burn_item()]1059        pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {10601061            let sender = ensure_signed(origin)?;10621063            // Transfer permissions check1064            let target_collection = Self::get_collection(collection_id)?;1065            ensure!(1066                Self::is_item_owner(sender.clone(), &target_collection, item_id) ||1067                (1068                    target_collection.limits.owner_can_transfer &&1069                    Self::is_owner_or_admin_permissions(&target_collection, sender.clone())1070                ),1071                Error::<T>::NoPermission1072            );10731074            if target_collection.access == AccessMode::WhiteList {1075                Self::check_white_list(&target_collection, &sender)?;1076            }10771078            match target_collection.mode1079            {1080                CollectionMode::NFT => Self::burn_nft_item(&target_collection, item_id)?,1081                CollectionMode::Fungible(_)  => Self::burn_fungible_item(&sender, &target_collection, value)?,1082                CollectionMode::ReFungible  => Self::burn_refungible_item(&target_collection, item_id, &sender)?,1083                _ => ()1084            };10851086            // call event1087            Self::deposit_event(RawEvent::ItemDestroyed(target_collection.id, item_id));10881089            Ok(())1090        }10911092        /// Change ownership of the token.1093        /// 1094        /// # Permissions1095        /// 1096        /// * Collection Owner1097        /// * Collection Admin1098        /// * Current NFT owner1099        ///1100        /// # Arguments1101        /// 1102        /// * recipient: Address of token recipient.1103        /// 1104        /// * collection_id.1105        /// 1106        /// * item_id: ID of the item1107        ///     * Non-Fungible Mode: Required.1108        ///     * Fungible Mode: Ignored.1109        ///     * Re-Fungible Mode: Required.1110        /// 1111        /// * value: Amount to transfer.1112        ///     * Non-Fungible Mode: Ignored1113        ///     * Fungible Mode: Must specify transferred amount1114        ///     * Re-Fungible Mode: Must specify transferred portion (between 0 and 1)1115        #[weight = <T as Config>::WeightInfo::transfer()]1116        pub fn transfer(origin, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResult {1117            let sender = ensure_signed(origin)?;1118            let collection = Self::get_collection(collection_id)?;11191120            Self::transfer_internal(sender, recipient, &collection, item_id, value)1121        }11221123        /// Set, change, or remove approved address to transfer the ownership of the NFT.1124        /// 1125        /// # Permissions1126        /// 1127        /// * Collection Owner1128        /// * Collection Admin1129        /// * Current NFT owner1130        /// 1131        /// # Arguments1132        /// 1133        /// * approved: Address that is approved to transfer this NFT or zero (if needed to remove approval).1134        /// 1135        /// * collection_id.1136        /// 1137        /// * item_id: ID of the item.1138        #[weight = <T as Config>::WeightInfo::approve()]1139        pub fn approve(origin, spender: T::AccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResult {11401141            let sender = ensure_signed(origin)?;1142            let target_collection = Self::get_collection(collection_id)?;11431144            Self::token_exists(&target_collection, item_id, &sender)?;11451146            // Transfer permissions check1147            let bypasses_limits = target_collection.limits.owner_can_transfer &&1148                Self::is_owner_or_admin_permissions(1149                    &target_collection,1150                    sender.clone(),1151                );11521153            let allowance_limit = if bypasses_limits {1154                None1155            } else if let Some(amount) = Self::owned_amount(1156                sender.clone(),1157                &target_collection,1158                item_id,1159            ) {1160                Some(amount)1161            } else {1162                fail!(Error::<T>::NoPermission);1163            };11641165            if target_collection.access == AccessMode::WhiteList {1166                Self::check_white_list(&target_collection, &sender)?;1167                Self::check_white_list(&target_collection, &spender)?;1168            }11691170            let allowance_exists = <Allowances<T>>::contains_key(collection_id, (item_id, &sender, &spender));1171            let mut allowance: u128 = amount;1172            if allowance_exists {1173                allowance += <Allowances<T>>::get(collection_id, (item_id, &sender, &spender));1174            }1175            if let Some(limit) = allowance_limit {1176                ensure!(limit >= allowance, Error::<T>::TokenValueTooLow);1177            }1178            <Allowances<T>>::insert(collection_id, (item_id, sender.clone(), spender.clone()), allowance);11791180            Ok(())1181        }1182        1183        /// Change ownership of a NFT on behalf of the owner. See Approve method for additional information. After this method executes, the approval is removed so that the approved address will not be able to transfer this NFT again from this owner.1184        /// 1185        /// # Permissions1186        /// * Collection Owner1187        /// * Collection Admin1188        /// * Current NFT owner1189        /// * Address approved by current NFT owner1190        /// 1191        /// # Arguments1192        /// 1193        /// * from: Address that owns token.1194        /// 1195        /// * recipient: Address of token recipient.1196        /// 1197        /// * collection_id.1198        /// 1199        /// * item_id: ID of the item.1200        /// 1201        /// * value: Amount to transfer.1202        #[weight = <T as Config>::WeightInfo::transfer_from()]1203        pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResult {12041205            let sender = ensure_signed(origin)?;1206            let target_collection = Self::get_collection(collection_id)?;12071208            let mut appoved_transfer = false;12091210            // Check approval1211            let mut approval: u128 = 0;1212            if <Allowances<T>>::contains_key(collection_id, (item_id, &from, &sender)) {1213                approval = <Allowances<T>>::get(collection_id, (item_id, &from, &sender));1214                ensure!(approval >= value, Error::<T>::TokenValueNotEnough);1215                appoved_transfer = true;1216            }12171218            // Limits check1219            Self::is_correct_transfer(&target_collection, &recipient)?;12201221            // Transfer permissions check         1222            ensure!(1223                appoved_transfer || 1224                (1225                    target_collection.limits.owner_can_transfer &&1226                    Self::is_owner_or_admin_permissions(&target_collection, sender.clone())1227                ),1228                Error::<T>::NoPermission1229            );12301231            if target_collection.access == AccessMode::WhiteList {1232                Self::check_white_list(&target_collection, &sender)?;1233                Self::check_white_list(&target_collection, &recipient)?;1234            }12351236            // Reduce approval by transferred amount or remove if remaining approval drops to 01237            if approval.checked_sub(value).unwrap_or(0) > 0 {1238                <Allowances<T>>::insert(collection_id, (item_id, &from, &sender), approval - value);1239            }1240            else {1241                <Allowances<T>>::remove(collection_id, (item_id, &from, &sender));1242            }12431244            match target_collection.mode1245            {1246                CollectionMode::NFT => Self::transfer_nft(&target_collection, item_id, from, recipient)?,1247                CollectionMode::Fungible(_)  => Self::transfer_fungible(&target_collection, value, &from, &recipient)?,1248                CollectionMode::ReFungible  => Self::transfer_refungible(&target_collection, item_id, value, from.clone(), recipient)?,1249                _ => ()1250            };12511252            Ok(())1253        }12541255        // #[weight = 0]1256        // pub fn safe_transfer_from(origin, collection_id: CollectionId, item_id: TokenId, new_owner: T::AccountId) -> DispatchResult {12571258        //     // let no_perm_mes = "You do not have permissions to modify this collection";1259        //     // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);1260        //     // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));1261        //     // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);12621263        //     // // on_nft_received  call12641265        //     // Self::transfer(origin, collection_id, item_id, new_owner)?;12661267        //     Ok(())1268        // }12691270        /// Set off-chain data schema.1271        /// 1272        /// # Permissions1273        /// 1274        /// * Collection Owner1275        /// * Collection Admin1276        /// 1277        /// # Arguments1278        /// 1279        /// * collection_id.1280        /// 1281        /// * schema: String representing the offchain data schema.1282        #[weight = <T as Config>::WeightInfo::set_variable_meta_data()]1283        pub fn set_variable_meta_data (1284            origin,1285            collection_id: CollectionId,1286            item_id: TokenId,1287            data: Vec<u8>1288        ) -> DispatchResult {1289            let sender = ensure_signed(origin)?;1290            1291            let target_collection = Self::get_collection(collection_id)?;1292            Self::token_exists(&target_collection, item_id, &sender)?;12931294            ensure!(ChainLimit::get().custom_data_limit >= data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);12951296            // Modify permissions check1297            ensure!(Self::is_item_owner(sender.clone(), &target_collection, item_id) ||1298                Self::is_owner_or_admin_permissions(&target_collection, sender.clone()),1299                Error::<T>::NoPermission);13001301            match target_collection.mode1302            {1303                CollectionMode::NFT => Self::set_nft_variable_data(&target_collection, item_id, data)?,1304                CollectionMode::ReFungible  => Self::set_re_fungible_variable_data(&target_collection, item_id, data)?,1305                CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),1306                _ => fail!(Error::<T>::UnexpectedCollectionType)1307            };13081309            Ok(())1310        }1311 1312        /// Set schema standard1313        /// ImageURL1314        /// Unique1315        /// 1316        /// # Permissions1317        /// 1318        /// * Collection Owner1319        /// * Collection Admin1320        /// 1321        /// # Arguments1322        /// 1323        /// * collection_id.1324        /// 1325        /// * schema: SchemaVersion: enum1326        #[weight = <T as Config>::WeightInfo::set_schema_version()]1327        pub fn set_schema_version(1328            origin,1329            collection_id: CollectionId,1330            version: SchemaVersion1331        ) -> DispatchResult {1332            let sender = ensure_signed(origin)?;1333            let mut target_collection = Self::get_collection(collection_id)?;1334            Self::check_owner_or_admin_permissions(&target_collection, sender.clone())?;1335            target_collection.schema_version = version;1336            Self::save_collection(target_collection);13371338            Ok(())1339        }13401341        /// Set off-chain data schema.1342        /// 1343        /// # Permissions1344        /// 1345        /// * Collection Owner1346        /// * Collection Admin1347        /// 1348        /// # Arguments1349        /// 1350        /// * collection_id.1351        /// 1352        /// * schema: String representing the offchain data schema.1353        #[weight = <T as Config>::WeightInfo::set_offchain_schema()]1354        pub fn set_offchain_schema(1355            origin,1356            collection_id: CollectionId,1357            schema: Vec<u8>1358        ) -> DispatchResult {1359            let sender = ensure_signed(origin)?;1360            let mut target_collection = Self::get_collection(collection_id)?;1361            Self::check_owner_or_admin_permissions(&target_collection, sender.clone())?;13621363            // check schema limit1364            ensure!(schema.len() as u32 <= ChainLimit::get().offchain_schema_limit, "");13651366            target_collection.offchain_schema = schema;1367            Self::save_collection(target_collection);13681369            Ok(())1370        }13711372        /// Set const on-chain data schema.1373        /// 1374        /// # Permissions1375        /// 1376        /// * Collection Owner1377        /// * Collection Admin1378        /// 1379        /// # Arguments1380        /// 1381        /// * collection_id.1382        /// 1383        /// * schema: String representing the const on-chain data schema.1384        #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1385        pub fn set_const_on_chain_schema (1386            origin,1387            collection_id: CollectionId,1388            schema: Vec<u8>1389        ) -> DispatchResult {1390            let sender = ensure_signed(origin)?;1391            let mut target_collection = Self::get_collection(collection_id)?;1392            Self::check_owner_or_admin_permissions(&target_collection, sender.clone())?;13931394            // check schema limit1395            ensure!(schema.len() as u32 <= ChainLimit::get().const_on_chain_schema_limit, "");13961397            target_collection.const_on_chain_schema = schema;1398            Self::save_collection(target_collection);13991400            Ok(())1401        }14021403        /// Set variable on-chain data schema.1404        /// 1405        /// # Permissions1406        /// 1407        /// * Collection Owner1408        /// * Collection Admin1409        /// 1410        /// # Arguments1411        /// 1412        /// * collection_id.1413        /// 1414        /// * schema: String representing the variable on-chain data schema.1415        #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1416        pub fn set_variable_on_chain_schema (1417            origin,1418            collection_id: CollectionId,1419            schema: Vec<u8>1420        ) -> DispatchResult {1421            let sender = ensure_signed(origin)?;1422            let mut target_collection = Self::get_collection(collection_id)?;1423            Self::check_owner_or_admin_permissions(&target_collection, sender.clone())?;14241425            // check schema limit1426            ensure!(schema.len() as u32 <= ChainLimit::get().variable_on_chain_schema_limit, "");14271428            target_collection.variable_on_chain_schema = schema;1429            Self::save_collection(target_collection);14301431            Ok(())1432        }14331434        // Sudo permissions function1435        #[weight = <T as Config>::WeightInfo::set_chain_limits()]1436        pub fn set_chain_limits(1437            origin,1438            limits: ChainLimits1439        ) -> DispatchResult {14401441            #[cfg(not(feature = "runtime-benchmarks"))]1442            ensure_root(origin)?;14431444            <ChainLimit>::put(limits);1445            Ok(())1446        }14471448        /// Enable smart contract self-sponsoring.1449        /// 1450        /// # Permissions1451        /// 1452        /// * Contract Owner1453        /// 1454        /// # Arguments1455        /// 1456        /// * contract address1457        /// * enable flag1458        /// 1459        #[weight = <T as Config>::WeightInfo::enable_contract_sponsoring()]1460        pub fn enable_contract_sponsoring(1461            origin,1462            contract_address: T::AccountId,1463            enable: bool1464        ) -> DispatchResult {14651466            let sender = ensure_signed(origin)?;14671468            #[cfg(feature = "runtime-benchmarks")]1469            <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());14701471            Self::ensure_contract_owned(sender, &contract_address)?;14721473            <ContractSelfSponsoring<T>>::insert(contract_address, enable);1474            Ok(())1475        }14761477        /// Set the rate limit for contract sponsoring to specified number of blocks.1478        /// 1479        /// If not set (has the default value of 0 blocks), the sponsoring will be disabled. 1480        /// If set to the number B (for blocks), the transactions will be sponsored with a rate 1481        /// limit of B, i.e. fees for every transaction sent to this smart contract will be paid 1482        /// from contract endowment if there are at least B blocks between such transactions. 1483        /// Nonetheless, if transactions are sent more frequently, the fees are paid by the sender.1484        /// 1485        /// # Permissions1486        /// 1487        /// * Contract Owner1488        /// 1489        /// # Arguments1490        /// 1491        /// -`contract_address`: Address of the contract to sponsor1492        /// -`rate_limit`: Number of blocks to wait until the next sponsored transaction is allowed1493        /// 1494        #[weight = <T as Config>::WeightInfo::set_contract_sponsoring_rate_limit()]1495        pub fn set_contract_sponsoring_rate_limit(1496            origin,1497            contract_address: T::AccountId,1498            rate_limit: T::BlockNumber1499        ) -> DispatchResult {1500            let sender = ensure_signed(origin)?;15011502            #[cfg(feature = "runtime-benchmarks")]1503            <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());15041505            Self::ensure_contract_owned(sender, &contract_address)?;1506            <ContractSponsoringRateLimit<T>>::insert(contract_address, rate_limit);1507            Ok(())1508        }15091510        /// Enable the white list for a contract. Only addresses added to the white list with addToContractWhiteList will be able to call this smart contract.1511        /// 1512        /// # Permissions1513        /// 1514        /// * Address that deployed smart contract.1515        /// 1516        /// # Arguments1517        /// 1518        /// -`contract_address`: Address of the contract.1519        /// 1520        /// - `enable`: .  1521        #[weight = <T as Config>::WeightInfo::toggle_contract_white_list()]1522        pub fn toggle_contract_white_list(1523            origin,1524            contract_address: T::AccountId,1525            enable: bool1526        ) -> DispatchResult {1527            let sender = ensure_signed(origin)?;15281529            #[cfg(feature = "runtime-benchmarks")]1530            <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());15311532            Self::ensure_contract_owned(sender, &contract_address)?;1533            <ContractWhiteListEnabled<T>>::insert(contract_address, enable);1534            Ok(())1535        }1536        1537        /// Add an address to smart contract white list.1538        /// 1539        /// # Permissions1540        /// 1541        /// * Address that deployed smart contract.1542        /// 1543        /// # Arguments1544        /// 1545        /// -`contract_address`: Address of the contract.1546        ///1547        /// -`account_address`: Address to add.1548        #[weight = <T as Config>::WeightInfo::add_to_contract_white_list()]1549        pub fn add_to_contract_white_list(1550            origin,1551            contract_address: T::AccountId,1552            account_address: T::AccountId1553        ) -> DispatchResult {1554            let sender = ensure_signed(origin)?;15551556            #[cfg(feature = "runtime-benchmarks")]1557            <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());1558            1559            Self::ensure_contract_owned(sender, &contract_address)?;      1560            <ContractWhiteList<T>>::insert(contract_address, account_address, true);1561            Ok(())1562        }15631564        /// Remove an address from smart contract white list.1565        /// 1566        /// # Permissions1567        /// 1568        /// * Address that deployed smart contract.1569        /// 1570        /// # Arguments1571        /// 1572        /// -`contract_address`: Address of the contract.1573        ///1574        /// -`account_address`: Address to remove.1575        #[weight = <T as Config>::WeightInfo::remove_from_contract_white_list()]1576        pub fn remove_from_contract_white_list(1577            origin,1578            contract_address: T::AccountId,1579            account_address: T::AccountId1580        ) -> DispatchResult {1581            let sender = ensure_signed(origin)?;15821583            #[cfg(feature = "runtime-benchmarks")]1584            <ContractOwner<T>>::insert(contract_address.clone(), sender.clone());15851586            Self::ensure_contract_owned(sender, &contract_address)?;1587            <ContractWhiteList<T>>::remove(contract_address, account_address);1588            Ok(())1589        }15901591        #[weight = <T as Config>::WeightInfo::set_collection_limits()]1592        pub fn set_collection_limits(1593            origin,1594            collection_id: u32,1595            new_limits: CollectionLimits<T::BlockNumber>,1596        ) -> DispatchResult {1597            let sender = ensure_signed(origin)?;1598            let mut target_collection = Self::get_collection(collection_id)?;1599            Self::check_owner_permissions(&target_collection, sender.clone())?;1600            let old_limits = &target_collection.limits;1601            let chain_limits = ChainLimit::get();16021603            // collection bounds1604            ensure!(new_limits.sponsor_transfer_timeout <= MAX_SPONSOR_TIMEOUT &&1605                new_limits.account_token_ownership_limit <= MAX_TOKEN_OWNERSHIP && 1606                new_limits.sponsored_data_size <= chain_limits.custom_data_limit,1607                Error::<T>::CollectionLimitBoundsExceeded);16081609            // token_limit   check  prev1610            ensure!(old_limits.token_limit >= new_limits.token_limit, Error::<T>::CollectionTokenLimitExceeded);1611            ensure!(new_limits.token_limit > 0, Error::<T>::CollectionTokenLimitExceeded);16121613            ensure!(1614                (old_limits.owner_can_transfer || !new_limits.owner_can_transfer) &&1615                (old_limits.owner_can_destroy || !new_limits.owner_can_destroy),1616                Error::<T>::OwnerPermissionsCantBeReverted,1617            );16181619            target_collection.limits = new_limits;1620            Self::save_collection(target_collection);16211622            Ok(())1623        } 1624    }1625}16261627impl<T: Config> Module<T> {16281629    pub fn transfer_internal(sender: T::AccountId, recipient: T::AccountId, target_collection: &CollectionHandle<T>, item_id: TokenId, value: u128) -> DispatchResult {1630        // Limits check1631        Self::is_correct_transfer(target_collection, &recipient)?;16321633        // Transfer permissions check1634        ensure!(Self::is_item_owner(sender.clone(), target_collection, item_id) ||1635            Self::is_owner_or_admin_permissions(target_collection, sender.clone()),1636            Error::<T>::NoPermission);16371638        if target_collection.access == AccessMode::WhiteList {1639            Self::check_white_list(target_collection, &sender)?;1640            Self::check_white_list(target_collection, &recipient)?;1641        }16421643        match target_collection.mode1644        {1645            CollectionMode::NFT => Self::transfer_nft(target_collection, item_id, sender.clone(), recipient.clone())?,1646            CollectionMode::Fungible(_)  => Self::transfer_fungible(target_collection, value, &sender, &recipient)?,1647            CollectionMode::ReFungible  => Self::transfer_refungible(target_collection, item_id, value, sender.clone(), recipient.clone())?,1648            _ => ()1649        };16501651        Self::deposit_event(RawEvent::Transfer(target_collection.id, item_id, sender, recipient, value));16521653        Ok(())1654    }165516561657    fn is_correct_transfer(collection: &CollectionHandle<T>, recipient: &T::AccountId) -> DispatchResult {1658        let collection_id = collection.id;16591660        // check token limit and account token limit1661        let account_items: u32 = <AddressTokens<T>>::get(collection_id, recipient).len() as u32;1662        ensure!(collection.limits.account_token_ownership_limit > account_items,  Error::<T>::AccountTokenLimitExceeded);1663        1664        Ok(())1665    }16661667    fn can_create_items_in_collection(collection: &CollectionHandle<T>, sender: &T::AccountId, owner: &T::AccountId) -> DispatchResult {1668        let collection_id = collection.id;16691670        // check token limit and account token limit1671        let total_items: u32 = ItemListIndex::get(collection_id);1672        let account_items: u32 = <AddressTokens<T>>::get(collection_id, owner).len() as u32;1673        ensure!(collection.limits.token_limit > total_items,  Error::<T>::CollectionTokenLimitExceeded);1674        ensure!(collection.limits.account_token_ownership_limit > account_items,  Error::<T>::AccountTokenLimitExceeded);16751676        if !Self::is_owner_or_admin_permissions(collection, sender.clone()) {1677            ensure!(collection.mint_mode == true, Error::<T>::PublicMintingNotAllowed);1678            Self::check_white_list(collection, owner)?;1679            Self::check_white_list(collection, sender)?;1680        }16811682        Ok(())1683    }16841685    fn validate_create_item_args(target_collection: &CollectionHandle<T>, data: &CreateItemData) -> DispatchResult {1686        match target_collection.mode1687        {1688            CollectionMode::NFT => {1689                if let CreateItemData::NFT(data) = data {1690                    // check sizes1691                    ensure!(ChainLimit::get().custom_data_limit >= data.const_data.len() as u32, Error::<T>::TokenConstDataLimitExceeded);1692                    ensure!(ChainLimit::get().custom_data_limit >= data.variable_data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);1693                } else {1694                    fail!(Error::<T>::NotNftDataUsedToMintNftCollectionToken);1695                }1696            },1697            CollectionMode::Fungible(_) => {1698                if let CreateItemData::Fungible(_) = data {1699                } else {1700                    fail!(Error::<T>::NotFungibleDataUsedToMintFungibleCollectionToken);1701                }1702            },1703            CollectionMode::ReFungible => {1704                if let CreateItemData::ReFungible(data) = data {17051706                    // check sizes1707                    ensure!(ChainLimit::get().custom_data_limit >= data.const_data.len() as u32, Error::<T>::TokenConstDataLimitExceeded);1708                    ensure!(ChainLimit::get().custom_data_limit >= data.variable_data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);17091710                    // Check refungibility limits1711                    ensure!(data.pieces <= MAX_REFUNGIBLE_PIECES, Error::<T>::WrongRefungiblePieces);1712                    ensure!(data.pieces > 0, Error::<T>::WrongRefungiblePieces);1713                } else {1714                    fail!(Error::<T>::NotReFungibleDataUsedToMintReFungibleCollectionToken);1715                }1716            },1717            _ => { fail!(Error::<T>::UnexpectedCollectionType); }1718        };17191720        Ok(())1721    }17221723    fn create_item_no_validation(collection: &CollectionHandle<T>, owner: T::AccountId, data: CreateItemData) -> DispatchResult {1724        let collection_id = collection.id;17251726        match data1727        {1728            CreateItemData::NFT(data) => {1729                let item = NftItemType {1730                    owner: owner.clone(),1731                    const_data: data.const_data,1732                    variable_data: data.variable_data1733                };17341735                Self::add_nft_item(collection, item)?;1736            },1737            CreateItemData::Fungible(data) => {1738                Self::add_fungible_item(collection, &owner, data.value)?;1739            },1740            CreateItemData::ReFungible(data) => {1741                let mut owner_list = Vec::new();1742                owner_list.push(Ownership {owner: owner.clone(), fraction: data.pieces});17431744                let item = ReFungibleItemType {1745                    owner: owner_list,1746                    const_data: data.const_data,1747                    variable_data: data.variable_data1748                };17491750                Self::add_refungible_item(collection, item)?;1751            }1752        };17531754        // call event1755        Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id), owner));17561757        Ok(())1758    }17591760    fn add_fungible_item(collection: &CollectionHandle<T>, owner: &T::AccountId, value: u128) -> DispatchResult {1761        let collection_id = collection.id;17621763        // Does new owner already have an account?1764        let mut balance: u128 = 0;1765        if <FungibleItemList<T>>::contains_key(collection_id, owner) {1766            balance = <FungibleItemList<T>>::get(collection_id, owner).value;1767        } 17681769        // Mint 1770        let item = FungibleItemType {1771            value: balance + value1772        };1773        <FungibleItemList<T>>::insert(collection_id, (*owner).clone(), item);17741775        // Update balance1776        let new_balance = <Balance<T>>::get(collection_id, owner)1777            .checked_add(value)1778            .ok_or(Error::<T>::NumOverflow)?;1779        <Balance<T>>::insert(collection_id, (*owner).clone(), new_balance);17801781        Ok(())1782    }17831784    fn add_refungible_item(collection: &CollectionHandle<T>, item: ReFungibleItemType<T::AccountId>) -> DispatchResult {1785        let collection_id = collection.id;17861787        let current_index = <ItemListIndex>::get(collection_id)1788            .checked_add(1)1789            .ok_or(Error::<T>::NumOverflow)?;1790        let itemcopy = item.clone();17911792        let value = item.owner.first().unwrap().fraction;1793        let owner = item.owner.first().unwrap().owner.clone();17941795        Self::add_token_index(collection_id, current_index, &owner)?;17961797        <ItemListIndex>::insert(collection_id, current_index);1798        <ReFungibleItemList<T>>::insert(collection_id, current_index, itemcopy);17991800        // Update balance1801        let new_balance = <Balance<T>>::get(collection_id, &owner)1802            .checked_add(value)1803            .ok_or(Error::<T>::NumOverflow)?;1804        <Balance<T>>::insert(collection_id, owner.clone(), new_balance);18051806        Ok(())1807    }18081809    fn add_nft_item(collection: &CollectionHandle<T>, item: NftItemType<T::AccountId>) -> DispatchResult {1810        let collection_id = collection.id;18111812        let current_index = <ItemListIndex>::get(collection_id)1813            .checked_add(1)1814            .ok_or(Error::<T>::NumOverflow)?;18151816        let item_owner = item.owner.clone();1817        Self::add_token_index(collection_id, current_index, &item.owner)?;18181819        <ItemListIndex>::insert(collection_id, current_index);1820        <NftItemList<T>>::insert(collection_id, current_index, item);18211822        // Update balance1823        let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())1824            .checked_add(1)1825            .ok_or(Error::<T>::NumOverflow)?;1826        <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);18271828        Ok(())1829    }18301831    fn burn_refungible_item(1832        collection: &CollectionHandle<T>,1833        item_id: TokenId,1834        owner: &T::AccountId,1835    ) -> DispatchResult {1836        let collection_id = collection.id;18371838        ensure!(1839            <ReFungibleItemList<T>>::contains_key(collection_id, item_id),1840            Error::<T>::TokenNotFound1841        );1842        let mut token = <ReFungibleItemList<T>>::get(collection_id, item_id);1843        let rft_balance = token1844            .owner1845            .iter()1846            .filter(|&i| i.owner == *owner)1847            .next()1848            .unwrap();1849        Self::remove_token_index(collection_id, item_id, owner)?;18501851        // update balance1852        let new_balance = <Balance<T>>::get(collection_id, rft_balance.owner.clone())1853            .checked_sub(rft_balance.fraction)1854            .ok_or(Error::<T>::NumOverflow)?;1855        <Balance<T>>::insert(collection_id, rft_balance.owner.clone(), new_balance);18561857        // Re-create owners list with sender removed1858        let index = token1859            .owner1860            .iter()1861            .position(|i| i.owner == *owner)1862            .unwrap();1863        token.owner.remove(index);1864        let owner_count = token.owner.len();18651866        // Burn the token completely if this was the last (only) owner1867        if owner_count == 0 {1868            <ReFungibleItemList<T>>::remove(collection_id, item_id);1869            <VariableMetaDataBasket<T>>::remove(collection_id, item_id);1870        }1871        else {1872            <ReFungibleItemList<T>>::insert(collection_id, item_id, token);1873        }18741875        Ok(())1876    }18771878    fn burn_nft_item(collection: &CollectionHandle<T>, item_id: TokenId) -> DispatchResult {1879        let collection_id = collection.id;18801881        ensure!(1882            <NftItemList<T>>::contains_key(collection_id, item_id),1883            Error::<T>::TokenNotFound1884        );1885        let item = <NftItemList<T>>::get(collection_id, item_id);1886        Self::remove_token_index(collection_id, item_id, &item.owner)?;18871888        // update balance1889        let new_balance = <Balance<T>>::get(collection_id, &item.owner)1890            .checked_sub(1)1891            .ok_or(Error::<T>::NumOverflow)?;1892        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);1893        <NftItemList<T>>::remove(collection_id, item_id);1894        <VariableMetaDataBasket<T>>::remove(collection_id, item_id);18951896        Ok(())1897    }18981899    fn burn_fungible_item(owner: &T::AccountId, collection: &CollectionHandle<T>, value: u128) -> DispatchResult {1900        let collection_id = collection.id;19011902        ensure!(1903            <FungibleItemList<T>>::contains_key(collection_id, owner),1904            Error::<T>::TokenNotFound1905        );1906        let mut balance = <FungibleItemList<T>>::get(collection_id, owner);1907        ensure!(balance.value >= value, Error::<T>::TokenValueNotEnough);19081909        // update balance1910        let new_balance = <Balance<T>>::get(collection_id, owner)1911            .checked_sub(value)1912            .ok_or(Error::<T>::NumOverflow)?;1913        <Balance<T>>::insert(collection_id, (*owner).clone(), new_balance);19141915        if balance.value - value > 0 {1916            balance.value -= value;1917            <FungibleItemList<T>>::insert(collection_id, (*owner).clone(), balance);1918        }1919        else {1920            <FungibleItemList<T>>::remove(collection_id, owner);1921        }19221923        Ok(())1924    }19251926    pub fn get_collection(collection_id: CollectionId) -> Result<CollectionHandle<T>, sp_runtime::DispatchError> {1927        Ok(<CollectionById<T>>::get(collection_id)1928            .map(|collection| CollectionHandle {1929                id: collection_id,1930                collection1931            })1932            .ok_or(Error::<T>::CollectionNotFound)?)1933    }19341935    fn save_collection(collection: CollectionHandle<T>) {1936        <CollectionById<T>>::insert(collection.id, collection.collection);1937    }19381939    fn check_owner_permissions(target_collection: &CollectionHandle<T>, subject: T::AccountId) -> DispatchResult {1940        ensure!(1941            subject == target_collection.owner,1942            Error::<T>::NoPermission1943        );19441945        Ok(())1946    }19471948    fn is_owner_or_admin_permissions(collection: &CollectionHandle<T>, subject: T::AccountId) -> bool {1949        let mut result: bool = subject == collection.owner;1950        let exists = <AdminList<T>>::contains_key(collection.id);19511952        if !result & exists {1953            if <AdminList<T>>::get(collection.id).contains(&subject) {1954                result = true1955            }1956        }19571958        result1959    }19601961    fn check_owner_or_admin_permissions(1962        collection: &CollectionHandle<T>,1963        subject: T::AccountId,1964    ) -> DispatchResult {1965        let result = Self::is_owner_or_admin_permissions(collection, subject.clone());19661967        ensure!(1968            result,1969            Error::<T>::NoPermission1970        );1971        Ok(())1972    }19731974    fn owned_amount(1975        subject: T::AccountId,1976        target_collection: &CollectionHandle<T>,1977        item_id: TokenId,1978    ) -> Option<u128> {1979        let collection_id = target_collection.id;19801981        match target_collection.mode {1982            CollectionMode::NFT => {1983                if <NftItemList<T>>::get(collection_id, item_id).owner == subject {1984                    return Some(1)1985                }1986                None1987            },1988            CollectionMode::Fungible(_) => {1989                if <FungibleItemList<T>>::contains_key(collection_id, &subject) {1990                    return Some(<FungibleItemList<T>>::get(collection_id, &subject)1991                        .value);1992                }1993                None1994            },1995            CollectionMode::ReFungible => <ReFungibleItemList<T>>::get(collection_id, item_id)1996                .owner1997                .iter()1998                .find(|i| i.owner == subject)1999                .map(|i| i.fraction),2000            CollectionMode::Invalid => None,2001        }2002    }20032004    fn is_item_owner(subject: T::AccountId, target_collection: &CollectionHandle<T>, item_id: TokenId) -> bool {2005        let collection_id = target_collection.id;20062007        match target_collection.mode {2008            CollectionMode::NFT => {2009                <NftItemList<T>>::get(collection_id, item_id).owner == subject2010            }2011            CollectionMode::Fungible(_) => {2012                <FungibleItemList<T>>::contains_key(collection_id, &subject)2013            }2014            CollectionMode::ReFungible => {2015                <ReFungibleItemList<T>>::get(collection_id, item_id)2016                    .owner2017                    .iter()2018                    .any(|i| i.owner == subject)2019            }2020            CollectionMode::Invalid => false,2021        }2022    }20232024    fn check_white_list(collection: &CollectionHandle<T>, address: &T::AccountId) -> DispatchResult {2025        let collection_id = collection.id;20262027        let mes = Error::<T>::AddresNotInWhiteList;2028        ensure!(<WhiteList<T>>::contains_key(collection_id, address), mes);20292030        Ok(())2031    }20322033    /// Check if token exists. In case of Fungible, check if there is an entry for 2034    /// the owner in fungible balances double map2035    fn token_exists(2036        target_collection: &CollectionHandle<T>,2037        item_id: TokenId,2038        owner: &T::AccountId2039    ) -> DispatchResult {2040        let collection_id = target_collection.id;2041        let exists = match target_collection.mode2042        {2043            CollectionMode::NFT => <NftItemList<T>>::contains_key(collection_id, item_id),2044            CollectionMode::Fungible(_)  => <FungibleItemList<T>>::contains_key(collection_id, owner),2045            CollectionMode::ReFungible  => <ReFungibleItemList<T>>::contains_key(collection_id, item_id),2046            _ => false2047        };20482049        ensure!(exists == true, Error::<T>::TokenNotFound);2050        Ok(())2051    }20522053    fn transfer_fungible(2054        collection: &CollectionHandle<T>,2055        value: u128,2056        owner: &T::AccountId,2057        recipient: &T::AccountId,2058    ) -> DispatchResult {2059        let collection_id = collection.id;2060        Self::token_exists(&collection, 0, owner)?;20612062        let mut balance = <FungibleItemList<T>>::get(collection_id, owner);2063        ensure!(balance.value >= value, Error::<T>::TokenValueTooLow);20642065        // Send balance to recipient (updates balanceOf of recipient)2066        Self::add_fungible_item(collection, recipient, value)?;20672068        // update balanceOf of sender2069        <Balance<T>>::insert(collection_id, (*owner).clone(), balance.value - value);20702071        // Reduce or remove sender2072        if balance.value == value {2073            <FungibleItemList<T>>::remove(collection_id, owner);2074        }2075        else {2076            balance.value -= value;2077            <FungibleItemList<T>>::insert(collection_id, (*owner).clone(), balance);2078        }20792080        Ok(())2081    }20822083    fn transfer_refungible(2084        collection: &CollectionHandle<T>,2085        item_id: TokenId,2086        value: u128,2087        owner: T::AccountId,2088        new_owner: T::AccountId,2089    ) -> DispatchResult {2090        let collection_id = collection.id;2091        Self::token_exists(collection, item_id, &owner)?;20922093        let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);2094        let item = full_item2095            .owner2096            .iter()2097            .filter(|i| i.owner == owner)2098            .next()2099            .ok_or(Error::<T>::NumOverflow)?;2100        let amount = item.fraction;21012102        ensure!(amount >= value, Error::<T>::TokenValueTooLow);21032104        // update balance2105        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())2106            .checked_sub(value)2107            .ok_or(Error::<T>::NumOverflow)?;2108        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);21092110        let balancenew_owner = <Balance<T>>::get(collection_id, new_owner.clone())2111            .checked_add(value)2112            .ok_or(Error::<T>::NumOverflow)?;2113        <Balance<T>>::insert(collection_id, new_owner.clone(), balancenew_owner);21142115        let old_owner = item.owner.clone();2116        let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);21172118        // transfer2119        if amount == value && !new_owner_has_account {2120            // change owner2121            // new owner do not have account2122            let mut new_full_item = full_item.clone();2123            new_full_item2124                .owner2125                .iter_mut()2126                .find(|i| i.owner == owner)2127                .unwrap()2128                .owner = new_owner.clone();2129            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);21302131            // update index collection2132            Self::move_token_index(collection_id, item_id, &old_owner, &new_owner)?;2133        } else {2134            let mut new_full_item = full_item.clone();2135            new_full_item2136                .owner2137                .iter_mut()2138                .find(|i| i.owner == owner)2139                .unwrap()2140                .fraction -= value;21412142            // separate amount2143            if new_owner_has_account {2144                // new owner has account2145                new_full_item2146                    .owner2147                    .iter_mut()2148                    .find(|i| i.owner == new_owner)2149                    .unwrap()2150                    .fraction += value;2151            } else {2152                // new owner do not have account2153                new_full_item.owner.push(Ownership {2154                    owner: new_owner.clone(),2155                    fraction: value,2156                });2157                Self::add_token_index(collection_id, item_id, &new_owner)?;2158            }21592160            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);2161        }21622163        Ok(())2164    }21652166    fn transfer_nft(2167        collection: &CollectionHandle<T>,2168        item_id: TokenId,2169        sender: T::AccountId,2170        new_owner: T::AccountId,2171    ) -> DispatchResult {2172        let collection_id = collection.id;2173        Self::token_exists(&collection, item_id, &sender)?;21742175        let mut item = <NftItemList<T>>::get(collection_id, item_id);21762177        ensure!(2178            sender == item.owner,2179            Error::<T>::MustBeTokenOwner2180        );21812182        // update balance2183        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())2184            .checked_sub(1)2185            .ok_or(Error::<T>::NumOverflow)?;2186        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);21872188        let balancenew_owner = <Balance<T>>::get(collection_id, new_owner.clone())2189            .checked_add(1)2190            .ok_or(Error::<T>::NumOverflow)?;2191        <Balance<T>>::insert(collection_id, new_owner.clone(), balancenew_owner);21922193        // change owner2194        let old_owner = item.owner.clone();2195        item.owner = new_owner.clone();2196        <NftItemList<T>>::insert(collection_id, item_id, item);21972198        // update index collection2199        Self::move_token_index(collection_id, item_id, &old_owner, &new_owner)?;22002201        Ok(())2202    }2203    2204    fn set_re_fungible_variable_data(2205        collection: &CollectionHandle<T>,2206        item_id: TokenId,2207        data: Vec<u8>2208    ) -> DispatchResult {2209        let collection_id = collection.id;2210        let mut item = <ReFungibleItemList<T>>::get(collection_id, item_id);22112212        item.variable_data = data;22132214        <ReFungibleItemList<T>>::insert(collection_id, item_id, item);22152216        Ok(())2217    }22182219    fn set_nft_variable_data(2220        collection: &CollectionHandle<T>,2221        item_id: TokenId,2222        data: Vec<u8>2223    ) -> DispatchResult {2224        let collection_id = collection.id;2225        let mut item = <NftItemList<T>>::get(collection_id, item_id);2226        2227        item.variable_data = data;22282229        <NftItemList<T>>::insert(collection_id, item_id, item);2230        2231        Ok(())2232    }22332234    fn init_collection(item: &Collection<T>) {2235        // check params2236        assert!(2237            item.decimal_points <= MAX_DECIMAL_POINTS,2238            "decimal_points parameter must be lower than MAX_DECIMAL_POINTS"2239        );2240        assert!(2241            item.name.len() <= 64,2242            "Collection name can not be longer than 63 char"2243        );2244        assert!(2245            item.name.len() <= 256,2246            "Collection description can not be longer than 255 char"2247        );2248        assert!(2249            item.token_prefix.len() <= 16,2250            "Token prefix can not be longer than 15 char"2251        );22522253        // Generate next collection ID2254        let next_id = CreatedCollectionCount::get()2255            .checked_add(1)2256            .unwrap();22572258        CreatedCollectionCount::put(next_id);2259    }22602261    fn init_nft_token(collection_id: CollectionId, item: &NftItemType<T::AccountId>) {2262        let current_index = <ItemListIndex>::get(collection_id)2263            .checked_add(1)2264            .unwrap();22652266        let item_owner = item.owner.clone();2267        Self::add_token_index(collection_id, current_index, &item.owner).unwrap();22682269        <ItemListIndex>::insert(collection_id, current_index);22702271        // Update balance2272        let new_balance = <Balance<T>>::get(collection_id, &item_owner)2273            .checked_add(1)2274            .unwrap();2275        <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);2276    }22772278    fn init_fungible_token(collection_id: CollectionId, owner: &T::AccountId, item: &FungibleItemType) {2279        let current_index = <ItemListIndex>::get(collection_id)2280            .checked_add(1)2281            .unwrap();22822283        Self::add_token_index(collection_id, current_index, owner).unwrap();22842285        <ItemListIndex>::insert(collection_id, current_index);22862287        // Update balance2288        let new_balance = <Balance<T>>::get(collection_id, owner)2289            .checked_add(item.value)2290            .unwrap();2291        <Balance<T>>::insert(collection_id, (*owner).clone(), new_balance);2292    }22932294    fn init_refungible_token(collection_id: CollectionId, item: &ReFungibleItemType<T::AccountId>) {2295        let current_index = <ItemListIndex>::get(collection_id)2296            .checked_add(1)2297            .unwrap();22982299        let value = item.owner.first().unwrap().fraction;2300        let owner = item.owner.first().unwrap().owner.clone();23012302        Self::add_token_index(collection_id, current_index, &owner).unwrap();23032304        <ItemListIndex>::insert(collection_id, current_index);23052306        // Update balance2307        let new_balance = <Balance<T>>::get(collection_id, &owner)2308            .checked_add(value)2309            .unwrap();2310        <Balance<T>>::insert(collection_id, owner.clone(), new_balance);2311    }23122313    fn add_token_index(collection_id: CollectionId, item_index: TokenId, owner: &T::AccountId) -> DispatchResult {2314        // add to account limit2315        if <AccountItemCount<T>>::contains_key(owner) {23162317            // bound Owned tokens by a single address2318            let count = <AccountItemCount<T>>::get(owner);2319            ensure!(count < ChainLimit::get().account_token_ownership_limit, Error::<T>::AddressOwnershipLimitExceeded);23202321            <AccountItemCount<T>>::insert(owner.clone(), count2322                .checked_add(1)2323                .ok_or(Error::<T>::NumOverflow)?);2324        }2325        else {2326            <AccountItemCount<T>>::insert(owner.clone(), 1);2327        }23282329        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner);2330        if list_exists {2331            let mut list = <AddressTokens<T>>::get(collection_id, owner);2332            let item_contains = list.contains(&item_index.clone());23332334            if !item_contains {2335                list.push(item_index.clone());2336            }23372338            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);2339        } else {2340            let mut itm = Vec::new();2341            itm.push(item_index.clone());2342            <AddressTokens<T>>::insert(collection_id, owner.clone(), itm);2343        }23442345        Ok(())2346    }23472348    fn remove_token_index(2349        collection_id: CollectionId,2350        item_index: TokenId,2351        owner: &T::AccountId,2352    ) -> DispatchResult {23532354        // update counter2355        <AccountItemCount<T>>::insert(owner.clone(), 2356            <AccountItemCount<T>>::get(owner)2357            .checked_sub(1)2358            .ok_or(Error::<T>::NumOverflow)?);235923602361        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner);2362        if list_exists {2363            let mut list = <AddressTokens<T>>::get(collection_id, owner);2364            let item_contains = list.contains(&item_index.clone());23652366            if item_contains {2367                list.retain(|&item| item != item_index);2368                <AddressTokens<T>>::insert(collection_id, owner.clone(), list);2369            }2370        }23712372        Ok(())2373    }23742375    fn move_token_index(2376        collection_id: CollectionId,2377        item_index: TokenId,2378        old_owner: &T::AccountId,2379        new_owner: &T::AccountId,2380    ) -> DispatchResult {2381        Self::remove_token_index(collection_id, item_index, old_owner)?;2382        Self::add_token_index(collection_id, item_index, new_owner)?;23832384        Ok(())2385    }2386    2387    fn ensure_contract_owned(account: T::AccountId, contract: &T::AccountId) -> DispatchResult {2388        if <ContractOwner<T>>::contains_key(contract.clone()) {2389            let owner = <ContractOwner<T>>::get(contract);2390            ensure!(account == owner, Error::<T>::NoPermission);2391        } else {2392            fail!(Error::<T>::NoPermission);2393        }23942395        Ok(())2396    }2397}23982399////////////////////////////////////////////////////////////////////////////////////////////////////2400// Economic models2401// #region24022403/// Fee multiplier.2404pub type Multiplier = FixedU128;24052406type BalanceOf<T> = <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::Balance;24072408/// Require the transactor pay for themselves and maybe include a tip to gain additional priority2409/// in the queue.2410#[derive(Encode, Decode, Clone, Eq, PartialEq)]2411pub struct ChargeTransactionPayment<T: Config>(#[codec(compact)] BalanceOf<T>);24122413impl<T: Config + Send + Sync> sp_std::fmt::Debug 2414    for ChargeTransactionPayment<T>2415{2416	#[cfg(feature = "std")]2417	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {2418		write!(f, "ChargeTransactionPayment<{:?}>", self.0)2419	}2420	#[cfg(not(feature = "std"))]2421	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {2422		Ok(())2423	}2424}24252426impl<T: Config> ChargeTransactionPayment<T>2427where2428    T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Call<T>> + IsSubType<pallet_contracts::Call<T>>,2429    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,2430    T::AccountId: AsRef<[u8]>,2431    T::AccountId: UncheckedFrom<T::Hash>,2432{2433    fn traditional_fee(2434        len: usize,2435        info: &DispatchInfoOf<T::Call>,2436        tip: BalanceOf<T>,2437    ) -> BalanceOf<T>2438    where2439        T::Call: Dispatchable<Info = DispatchInfo>,2440    {2441        <pallet_transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)2442    }24432444	fn get_priority(len: usize, info: &DispatchInfoOf<T::Call>, final_fee: BalanceOf<T>) -> TransactionPriority {2445        let weight_saturation = T::BlockWeights::get().max_block / info.weight.max(1);2446        let max_block_length = *T::BlockLength::get().max.get(DispatchClass::Normal);2447        let len_saturation = max_block_length as u64 / (len as u64).max(1);2448        let coefficient: BalanceOf<T> = weight_saturation2449            .min(len_saturation)2450            .saturated_into::<BalanceOf<T>>();2451        final_fee2452            .saturating_mul(coefficient)2453            .saturated_into::<TransactionPriority>()2454    }24552456    fn withdraw_fee(2457        &self,2458        who: &T::AccountId,2459        call: &T::Call,2460        info: &DispatchInfoOf<T::Call>,2461        len: usize,2462	) -> Result<2463		(2464			BalanceOf<T>,2465			<<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::LiquidityInfo,2466		),2467		TransactionValidityError,2468	> {2469        let tip = self.0;24702471        // Set fee based on call type. Creating collection costs 1 Unique.2472        // All other transactions have traditional fees so far2473        // let fee = match call.is_sub_type() {2474        //     Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),2475        //     _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes2476        //                                                 // _ => <BalanceOf<T>>::from(100)2477        // };2478        let fee = Self::traditional_fee(len, info, tip);24792480        // Only mess with balances if fee is not zero.2481        if fee.is_zero() {2482            return <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::withdraw_fee(who, call, info, fee, tip)2483			.map(|i| (fee, i));2484        }24852486        // Determine who is paying transaction fee based on ecnomic model2487        // Parse call to extract collection ID and access collection sponsor2488        let mut sponsor: Option<T::AccountId> = (|| match IsSubType::<Call<T>>::is_sub_type(call) {2489            Some(Call::create_item(collection_id, _owner, _properties)) => {2490                let collection = <CollectionById<T>>::get(collection_id)?;24912492                // sponsor timeout2493                let block_number = <system::Module<T>>::block_number() as T::BlockNumber;24942495                let limit = collection.limits.sponsor_transfer_timeout;2496                if <CreateItemBasket<T>>::contains_key((collection_id, &who)) {2497                    let last_tx_block = <CreateItemBasket<T>>::get((collection_id, &who));2498                    let limit_time = last_tx_block + limit.into();2499                    if block_number <= limit_time {2500                        return None;2501                    }2502                }2503                <CreateItemBasket<T>>::insert((collection_id, who.clone()), block_number);25042505                // check free create limit2506                if (collection.limits.sponsored_data_size >= (_properties.len() as u32)) &&2507                   (collection.sponsor_confirmed)2508                {2509                    Some(collection.sponsor)2510                } else {2511                    None2512                }2513            }2514            Some(Call::transfer(_new_owner, collection_id, item_id, _value)) => {2515                let collection = <CollectionById<T>>::get(collection_id)?;2516                2517                let mut sponsor_transfer = false;2518                if collection.sponsor_confirmed {25192520                    let collection_limits = collection.limits;2521                    let collection_mode = collection.mode;2522    2523                    // sponsor timeout2524                    let block_number = <system::Module<T>>::block_number() as T::BlockNumber;2525                    sponsor_transfer = match collection_mode {2526                        CollectionMode::NFT => {2527    2528                            // get correct limit2529                            let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {2530                                collection_limits.sponsor_transfer_timeout2531                            } else {2532                                ChainLimit::get().nft_sponsor_transfer_timeout2533                            };2534    2535                            let mut sponsored = true;2536                            if <NftTransferBasket<T>>::contains_key(collection_id, item_id) {2537                                let last_tx_block = <NftTransferBasket<T>>::get(collection_id, item_id);2538                                let limit_time = last_tx_block + limit.into();2539                                if block_number <= limit_time {2540                                    sponsored = false;2541                                }2542                            }2543                            if sponsored {2544                                <NftTransferBasket<T>>::insert(collection_id, item_id, block_number);2545                            }25462547                            sponsored2548                        }2549                        CollectionMode::Fungible(_) => {2550    2551                            // get correct limit2552                            let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {2553                                collection_limits.sponsor_transfer_timeout2554                            } else {2555                                ChainLimit::get().fungible_sponsor_transfer_timeout2556                            };2557    2558                            let block_number = <system::Module<T>>::block_number() as T::BlockNumber;2559                            let mut sponsored = true;2560                            if <FungibleTransferBasket<T>>::contains_key(collection_id, who) {2561                                let last_tx_block = <FungibleTransferBasket<T>>::get(collection_id, who);2562                                let limit_time = last_tx_block + limit.into();2563                                if block_number <= limit_time {2564                                    sponsored = false;2565                                }2566                            }2567                            if sponsored {2568                                <FungibleTransferBasket<T>>::insert(collection_id, who, block_number);2569                            }25702571                            sponsored2572                        }2573                        CollectionMode::ReFungible => {2574    2575                            // get correct limit2576                            let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {2577                                collection_limits.sponsor_transfer_timeout2578                            } else {2579                                ChainLimit::get().refungible_sponsor_transfer_timeout2580                            };2581    2582                            let mut sponsored = true;2583                            if <ReFungibleTransferBasket<T>>::contains_key(collection_id, item_id) {2584                                let last_tx_block = <ReFungibleTransferBasket<T>>::get(collection_id, item_id);2585                                let limit_time = last_tx_block + limit.into();2586                                if block_number <= limit_time {2587                                    sponsored = false;2588                                }2589                            }2590                            if sponsored {2591                                <ReFungibleTransferBasket<T>>::insert(collection_id, item_id, block_number);2592                            }25932594                            sponsored2595                        }2596                        _ => {2597                            false2598                        },2599                    };2600                }26012602                if !sponsor_transfer {2603                    None2604                } else {2605                    Some(collection.sponsor)2606                }2607            }26082609            Some(Call::set_variable_meta_data(collection_id, item_id, data)) => {2610                let mut sponsor_metadata_changes = false;26112612                let collection = <CollectionById<T>>::get(collection_id)?;26132614                if2615                    collection.sponsor_confirmed &&2616                    // Can't sponsor fungible collection, this tx will be rejected2617                    // as invalid2618                    !matches!(collection.mode, CollectionMode::Fungible(_)) &&2619                    data.len() <= collection.limits.sponsored_data_size as usize2620                {2621                    if let Some(rate_limit) = collection.limits.sponsored_data_rate_limit {2622                        let block_number = <system::Module<T>>::block_number() as T::BlockNumber;26232624                        if <VariableMetaDataBasket<T>>::get(collection_id, item_id)2625                            .map(|last_block| block_number - last_block > rate_limit)2626                            .unwrap_or(true) 2627                        {2628                            sponsor_metadata_changes = true;2629                            <VariableMetaDataBasket<T>>::insert(collection_id, item_id, block_number);2630                        }2631                    }2632                }26332634                if !sponsor_metadata_changes {2635                    None2636                } else {2637                    Some(collection.sponsor)2638                }2639            }26402641            _ => None,2642        })();26432644        match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {2645            Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {26462647                let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());26482649                let owned_contract = <ContractOwner<T>>::contains_key(called_contract.clone())2650                  && <ContractOwner<T>>::get(called_contract.clone()) == *who;2651                let white_list_enabled = <ContractWhiteListEnabled<T>>::contains_key(called_contract.clone()) && <ContractWhiteListEnabled<T>>::get(called_contract.clone());2652                  2653                if !owned_contract && white_list_enabled {2654                    if !<ContractWhiteList<T>>::contains_key(called_contract.clone(), who) {2655                        return Err(InvalidTransaction::Call.into());2656                    }2657                }2658            },2659            _ => {},2660        }26612662        // Sponsor smart contracts2663        sponsor = sponsor.or_else(|| match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {26642665            // On instantiation: set the contract owner2666            Some(pallet_contracts::Call::instantiate(_endowment, _gas_limit, code_hash, _data, salt)) => {26672668                let new_contract_address = <pallet_contracts::Module<T>>::contract_address(2669                    &who,2670                    code_hash,2671                    salt,2672                );2673                <ContractOwner<T>>::insert(new_contract_address.clone(), who.clone());26742675                None2676            },26772678            // On instantiation with code: set the contract owner2679            Some(pallet_contracts::Call::instantiate_with_code(_endowment, _gas_limit, _code, _data, _salt))  => {26802681                let new_contract_address = <pallet_contracts::Module<T>>::contract_address(2682                    &who,2683                    &T::Hashing::hash(&_code),2684                    _salt,2685                );26862687                <ContractOwner<T>>::insert(new_contract_address.clone(), who.clone());26882689                None2690            }26912692            // When the contract is called, check if the sponsoring is enabled and pay fees from contract endowment if it is2693            Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {26942695                let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());26962697                let mut sponsor_transfer = false;2698                if <ContractSponsoringRateLimit<T>>::contains_key(called_contract.clone()) {2699                    let last_tx_block = <ContractSponsorBasket<T>>::get((&called_contract, &who));2700                    let block_number = <system::Module<T>>::block_number() as T::BlockNumber;2701                    let rate_limit = <ContractSponsoringRateLimit<T>>::get(&called_contract);2702                    let limit_time = last_tx_block + rate_limit;27032704                    if block_number >= limit_time {2705                        <ContractSponsorBasket<T>>::insert((called_contract.clone(), who.clone()), block_number);2706                        sponsor_transfer = true;2707                    }2708                } else {2709                    sponsor_transfer = false;2710                }2711               2712                if sponsor_transfer {2713                    if <ContractSelfSponsoring<T>>::contains_key(called_contract.clone()) {2714                        if <ContractSelfSponsoring<T>>::get(called_contract.clone()) {2715                            return Some(called_contract);2716                        }2717                    }2718                }27192720                None2721            },27222723            _ => None,2724        });27252726        let who_pays_fee = sponsor.unwrap_or_else(|| who.clone());27272728		<<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::withdraw_fee(&who_pays_fee, call, info, fee, tip)2729			.map(|i| (fee, i))2730    }2731}273227332734impl<T: Config + Send + Sync> SignedExtension2735    for ChargeTransactionPayment<T>2736where2737    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,2738    T::Call: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Call<T>> + IsSubType<pallet_contracts::Call<T>>,2739    T::AccountId: AsRef<[u8]>,2740    T::AccountId: UncheckedFrom<T::Hash>,2741{2742    const IDENTIFIER: &'static str = "ChargeTransactionPayment";2743    type AccountId = T::AccountId;2744    type Call = T::Call;2745    type AdditionalSigned = ();2746    type Pre = (2747        // tip2748        BalanceOf<T>,2749        // who pays fee2750        Self::AccountId,2751		// imbalance resulting from withdrawing the fee2752		<<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::LiquidityInfo,2753    );2754    fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {2755        Ok(())2756    }27572758    fn validate(2759        &self,2760        who: &Self::AccountId,2761        call: &Self::Call,2762        info: &DispatchInfoOf<Self::Call>,2763        len: usize,2764    ) -> TransactionValidity {2765		let (fee, _) = self.withdraw_fee(who, call, info, len)?;2766		Ok(ValidTransaction {2767			priority: Self::get_priority(len, info, fee),2768			..Default::default()2769		})2770    }27712772    fn pre_dispatch(2773        self,2774        who: &Self::AccountId,2775        call: &Self::Call,2776        info: &DispatchInfoOf<Self::Call>,2777        len: usize,2778    ) -> Result<Self::Pre, TransactionValidityError> {2779        let (_fee, imbalance) = self.withdraw_fee(who, call, info, len)?;2780        Ok((self.0, who.clone(), imbalance))2781    }27822783    fn post_dispatch(2784        pre: Self::Pre,2785        info: &DispatchInfoOf<Self::Call>,2786        post_info: &PostDispatchInfoOf<Self::Call>,2787        len: usize,2788        _result: &DispatchResult,2789    ) -> Result<(), TransactionValidityError> {2790		let (tip, who, imbalance) = pre;2791		let actual_fee = pallet_transaction_payment::Module::<T>::compute_actual_fee(2792			len as u32,2793			info,2794			post_info,2795			tip,2796		);2797		<T as pallet_transaction_payment::Config>::OnChargeTransaction::correct_and_deposit_fee(&who, info, post_info, actual_fee, tip, imbalance)?;2798		Ok(())2799    }2800}28012802// #endregion