git.delta.rocks / unique-network / refs/commits / 7fa5eef78e38

difftreelog

source

pallets/nft/src/lib.rs49.1 KiBsourcehistory
1#![cfg_attr(not(feature = "std"), no_std)]23/// For more guidance on Substrate FRAME, see the example pallet4/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs5use codec::{Decode, Encode};6pub use frame_support::{7    construct_runtime, decl_event, decl_module, decl_storage,8    dispatch::DispatchResult,9    ensure, parameter_types,10    traits::{11        Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,12        Randomness, WithdrawReason,13    },14    weights::{15        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},16        DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,17        WeightToFeePolynomial,18    },19    IsSubType, StorageValue,20};2122use frame_system::{self as system, ensure_signed};23use sp_runtime::sp_std::prelude::Vec;24use sp_runtime::{25    traits::{26        DispatchInfoOf, Dispatchable, PostDispatchInfoOf, SaturatedConversion, Saturating,27        SignedExtension, Zero,28    },29    transaction_validity::{30        InvalidTransaction, TransactionPriority, TransactionValidity, TransactionValidityError,31        ValidTransaction,32    },33    FixedPointOperand, FixedU128,34};35use sp_std::prelude::*;3637#[cfg(test)]38mod mock;3940#[cfg(test)]41mod tests;4243#[derive(Encode, Decode, Debug, Eq, Clone, PartialEq)]44pub enum CollectionMode {45    Invalid,46    // custom data size47    NFT(u32),48    // decimal points49    Fungible(u32),50    // custom data size and decimal points51    ReFungible(u32, u32),52}5354impl Into<u8> for CollectionMode {55    fn into(self) -> u8 {56        match self {57            CollectionMode::Invalid => 0,58            CollectionMode::NFT(_) => 1,59            CollectionMode::Fungible(_) => 2,60            CollectionMode::ReFungible(_, _) => 3,61        }62    }63}6465#[derive(Encode, Decode, Debug, Clone, PartialEq)]66pub enum AccessMode {67    Normal,68    WhiteList,69}70impl Default for AccessMode {71    fn default() -> Self {72        Self::Normal73    }74}7576impl Default for CollectionMode {77    fn default() -> Self {78        Self::Invalid79    }80}8182#[derive(Encode, Decode, Default, Clone, PartialEq)]83#[cfg_attr(feature = "std", derive(Debug))]84pub struct Ownership<AccountId> {85    pub owner: AccountId,86    pub fraction: u128,87}8889#[derive(Encode, Decode, Default, Clone, PartialEq)]90#[cfg_attr(feature = "std", derive(Debug))]91pub struct CollectionType<AccountId> {92    pub owner: AccountId,93    pub mode: CollectionMode,94    pub access: AccessMode,95    pub decimal_points: u32,96    pub name: Vec<u16>,        // 64 include null escape char97    pub description: Vec<u16>, // 256 include null escape char98    pub token_prefix: Vec<u8>, // 16 include null escape char99    pub custom_data_size: u32,100    pub mint_mode: bool,101    pub offchain_schema: Vec<u8>,102    pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender103    pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship104}105106#[derive(Encode, Decode, Default, Clone, PartialEq)]107#[cfg_attr(feature = "std", derive(Debug))]108pub struct CollectionAdminsType<AccountId> {109    pub admin: AccountId,110    pub collection_id: u64,111}112113#[derive(Encode, Decode, Default, Clone, PartialEq)]114#[cfg_attr(feature = "std", derive(Debug))]115pub struct NftItemType<AccountId> {116    pub collection: u64,117    pub owner: AccountId,118    pub data: Vec<u8>,119}120121#[derive(Encode, Decode, Default, Clone, PartialEq)]122#[cfg_attr(feature = "std", derive(Debug))]123pub struct FungibleItemType<AccountId> {124    pub collection: u64,125    pub owner: AccountId,126    pub value: u128,127}128129#[derive(Encode, Decode, Default, Clone, PartialEq)]130#[cfg_attr(feature = "std", derive(Debug))]131pub struct ReFungibleItemType<AccountId> {132    pub collection: u64,133    pub owner: Vec<Ownership<AccountId>>,134    pub data: Vec<u8>,135}136137#[derive(Encode, Decode, Default, Clone, PartialEq)]138#[cfg_attr(feature = "std", derive(Debug))]139pub struct ApprovePermissions<AccountId> {140    pub approved: AccountId,141    pub amount: u64,142}143144#[derive(Encode, Decode, Default, Clone, PartialEq)]145#[cfg_attr(feature = "std", derive(Debug))]146pub struct VestingItem<AccountId, Moment> {147    pub sender: AccountId,148    pub recipient: AccountId,149    pub collection_id: u64,150    pub item_id: u64,151    pub amount: u64,152    pub vesting_date: Moment,153}154155pub trait Trait: system::Trait {156    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;157}158159decl_storage! {160    trait Store for Module<T: Trait> as Nft {161162        // Private members163        NextCollectionID: u64;164        CreatedCollectionCount: u64;165        ChainVersion: u64;166        ItemListIndex: map hasher(blake2_128_concat) u64 => u64;167168        pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;169        pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;170        pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;171172        /// Balance owner per collection map173        pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;174175        /// second parameter: item id + owner account id176        pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) (u64, T::AccountId) => Vec<ApprovePermissions<T::AccountId>>;177178        /// Item collections179        pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;180        pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;181        pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;182183        /// Index list184        pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;185186        // Sponsorship187        pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;188        pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;189    }190}191192decl_event!(193    pub enum Event<T>194    where195        AccountId = <T as system::Trait>::AccountId,196    {197        Created(u64, u8, AccountId),198        ItemCreated(u64, u64),199        ItemDestroyed(u64, u64),200    }201);202203decl_module! {204    pub struct Module<T: Trait> for enum Call where origin: T::Origin {205206        fn deposit_event() = default;207208        fn on_initialize(now: T::BlockNumber) -> Weight {209210            if ChainVersion::get() < 2211            {212                let value = NextCollectionID::get();213                CreatedCollectionCount::put(value);214                ChainVersion::put(2);215            }216217            0218        }219220        // Create collection of NFT with given parameters221        //222        // @param customDataSz size of custom data in each collection item223        // returns collection ID224        #[weight = 0]225        pub fn create_collection(origin,226                                 collection_name: Vec<u16>,227                                 collection_description: Vec<u16>,228                                 token_prefix: Vec<u8>,229                                 mode: CollectionMode) -> DispatchResult {230231            // Anyone can create a collection232            let who = ensure_signed(origin)?;233            let custom_data_size = match mode {234                CollectionMode::NFT(size) => size,235                CollectionMode::ReFungible(size, _) => size,236                _ => 0237            };238239            let decimal_points = match mode {240                CollectionMode::Fungible(points) => points,241                CollectionMode::ReFungible(_, points) => points,242                _ => 0243            };244245            // check params246            ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4");247248            let mut name = collection_name.to_vec();249            name.push(0);250            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");251252            let mut description = collection_description.to_vec();253            description.push(0);254            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");255256            let mut prefix = token_prefix.to_vec();257            prefix.push(0);258            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");259260            // Generate next collection ID261            let next_id = CreatedCollectionCount::get()262                .checked_add(1)263                .expect("collection id error");264265            CreatedCollectionCount::put(next_id);266267            // Create new collection268            let new_collection = CollectionType {269                owner: who.clone(),270                name: name,271                mode: mode.clone(),272                mint_mode: false,273                access: AccessMode::Normal,274                description: description,275                decimal_points: decimal_points,276                token_prefix: prefix,277                offchain_schema: Vec::new(),278                custom_data_size: custom_data_size,279                sponsor: T::AccountId::default(),280                unconfirmed_sponsor: T::AccountId::default(),281            };282283            // Add new collection to map284            <Collection<T>>::insert(next_id, new_collection);285286            // call event287            Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));288289            Ok(())290        }291292        #[weight = 0]293        pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {294295            let sender = ensure_signed(origin)?;296            Self::check_owner_permissions(collection_id, sender)?;297298            // TODO Items remove299            <AddressTokens<T>>::remove_prefix(collection_id);300            <ApprovedList<T>>::remove_prefix(collection_id);301            <Balance<T>>::remove_prefix(collection_id);302            <ItemListIndex>::remove(collection_id);303            <AdminList<T>>::remove(collection_id);304            <Collection<T>>::remove(collection_id);305            <WhiteList<T>>::remove(collection_id);306307            Ok(())308        }309310        #[weight = 0]311        pub fn add_to_white_list(origin, collection_id: u64, address: T::AccountId) -> DispatchResult{312313            let sender = ensure_signed(origin)?;314            Self::check_owner_or_admin_permissions(collection_id, sender)?;315316            let mut white_list_collection: Vec<T::AccountId>;317            if <WhiteList<T>>::contains_key(collection_id) {318                white_list_collection = <WhiteList<T>>::get(collection_id);319                if !white_list_collection.contains(&address.clone())320                {321                    white_list_collection.push(address.clone());322                }323            }324            else {325                white_list_collection = Vec::new();326                white_list_collection.push(address.clone());327            }328329            <WhiteList<T>>::insert(collection_id, white_list_collection);330            Ok(())331        }332333        #[weight = 0]334        pub fn remove_from_white_list(origin, collection_id: u64, address: T::AccountId) -> DispatchResult{335336            let sender = ensure_signed(origin)?;337            Self::check_owner_or_admin_permissions(collection_id, sender)?;338339            if <WhiteList<T>>::contains_key(collection_id) {340                let mut white_list_collection = <WhiteList<T>>::get(collection_id);341                if white_list_collection.contains(&address.clone())342                {343                    white_list_collection.retain(|i| *i != address.clone());344                    <WhiteList<T>>::insert(collection_id, white_list_collection);345                }346            }347348            Ok(())349        }350351        #[weight = 0]352        pub fn set_public_access_mode(origin, collection_id: u64, mode: AccessMode) -> DispatchResult353        {354            let sender = ensure_signed(origin)?;355356            Self::check_owner_permissions(collection_id, sender)?;357            let mut target_collection = <Collection<T>>::get(collection_id);358            target_collection.access = mode;359            <Collection<T>>::insert(collection_id, target_collection);360361            Ok(())362        }363364        #[weight = 0]365        pub fn set_mint_permission(origin, collection_id: u64, mint_permission: bool) -> DispatchResult366        {367            let sender = ensure_signed(origin)?;368369            Self::check_owner_permissions(collection_id, sender)?;370            let mut target_collection = <Collection<T>>::get(collection_id);371            target_collection.mint_mode = mint_permission;372            <Collection<T>>::insert(collection_id, target_collection);373374            Ok(())375        }376377        #[weight = 0]378        pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {379380            let sender = ensure_signed(origin)?;381            Self::check_owner_permissions(collection_id, sender)?;382            let mut target_collection = <Collection<T>>::get(collection_id);383            target_collection.owner = new_owner;384            <Collection<T>>::insert(collection_id, target_collection);385386            Ok(())387        }388389        #[weight = 0]390        pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {391392            let sender = ensure_signed(origin)?;393            Self::check_owner_or_admin_permissions(collection_id, sender)?;394            let mut admin_arr: Vec<T::AccountId> = Vec::new();395396            if <AdminList<T>>::contains_key(collection_id)397            {398                admin_arr = <AdminList<T>>::get(collection_id);399                ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");400            }401402            admin_arr.push(new_admin_id);403            <AdminList<T>>::insert(collection_id, admin_arr);404405            Ok(())406        }407408        #[weight = 0]409        pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {410411            let sender = ensure_signed(origin)?;412            Self::check_owner_or_admin_permissions(collection_id, sender)?;413414            if <AdminList<T>>::contains_key(collection_id)415            {416                let mut admin_arr = <AdminList<T>>::get(collection_id);417                admin_arr.retain(|i| *i != account_id);418                <AdminList<T>>::insert(collection_id, admin_arr);419            }420421            Ok(())422        }423424        #[weight = 0]425        pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {426427            let sender = ensure_signed(origin)?;428            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");429430            let mut target_collection = <Collection<T>>::get(collection_id);431            ensure!(sender == target_collection.owner, "You do not own this collection");432433            target_collection.unconfirmed_sponsor = new_sponsor;434            <Collection<T>>::insert(collection_id, target_collection);435436            Ok(())437        }438439        #[weight = 0]440        pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {441442            let sender = ensure_signed(origin)?;443            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");444445            let mut target_collection = <Collection<T>>::get(collection_id);446            ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");447448            target_collection.sponsor = target_collection.unconfirmed_sponsor;449            target_collection.unconfirmed_sponsor = T::AccountId::default();450            <Collection<T>>::insert(collection_id, target_collection);451452            Ok(())453        }454455        #[weight = 0]456        pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {457458            let sender = ensure_signed(origin)?;459            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");460461            let mut target_collection = <Collection<T>>::get(collection_id);462            ensure!(sender == target_collection.owner, "You do not own this collection");463464            target_collection.sponsor = T::AccountId::default();465            <Collection<T>>::insert(collection_id, target_collection);466467            Ok(())468        }469470        #[weight = 0]471        pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {472473            let sender = ensure_signed(origin)?;474            Self::collection_exists(collection_id)?;475            let target_collection = <Collection<T>>::get(collection_id);476477            if !Self::is_owner_or_admin_permissions(collection_id, sender.clone()) {478                if target_collection.mint_mode == false {479                    panic!("Collection is not in mint mode");480                }481482                Self::check_white_list(collection_id, owner.clone())?;483            }484485            match target_collection.mode486            {487                CollectionMode::NFT(_) => {488489                    // check size490                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");491492                    // Create nft item493                    let item = NftItemType {494                        collection: collection_id,495                        owner: owner,496                        data: properties.clone(),497                    };498499                    Self::add_nft_item(item)?;500501                },502                CollectionMode::Fungible(_) => {503504                    // check size505                    ensure!(properties.len() as u32 == 0, "Size of item must be 0 with fungible type");506507                    let item = FungibleItemType {508                        collection: collection_id,509                        owner: owner,510                        value: (10 as u128).pow(target_collection.decimal_points)511                    };512513                    Self::add_fungible_item(item)?;514                },515                CollectionMode::ReFungible(_, _) => {516517                    // check size518                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");519520                    let mut owner_list = Vec::new();521                    let value = (10 as u128).pow(target_collection.decimal_points);522                    owner_list.push(Ownership {owner: owner.clone(), fraction: value});523524                    let item = ReFungibleItemType {525                        collection: collection_id,526                        owner: owner_list,527                        data: properties.clone()528                    };529530                    Self::add_refungible_item(item)?;531                },532                _ => { ensure!(1 == 0,"just error"); }533534            };535536            // call event537            Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));538539            Ok(())540        }541542        #[weight = 0]543        pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {544545            let sender = ensure_signed(origin)?;546            Self::collection_exists(collection_id)?;547            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);548            if !item_owner549            {550                if !Self::is_owner_or_admin_permissions(collection_id, sender.clone()) {  551                    Self::check_white_list(collection_id, sender.clone())?;552                }553            }554            let target_collection = <Collection<T>>::get(collection_id);555556            match target_collection.mode557            {558                CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,559                CollectionMode::Fungible(_)  => Self::burn_fungible_item(collection_id, item_id)?,560                CollectionMode::ReFungible(_, _)  => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,561                _ => ()562            };563564            // call event565            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));566567            Ok(())568        }569570        #[weight = 0]571        pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {572573            let sender = ensure_signed(origin)?;574575            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);576            if !item_owner {577                Self::check_white_list(collection_id, sender.clone())?;578                Self::check_white_list(collection_id, recipient.clone())?;579            }580581            let target_collection = <Collection<T>>::get(collection_id);582583            match target_collection.mode584            {585                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,586                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,587                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,588                _ => ()589            };590591            Ok(())592        }593594        #[weight = 0]595        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {596597            let sender = ensure_signed(origin)?;598599            // amount param stub600            let amount = 100000000;601602            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);603            if !item_owner {604                Self::check_white_list(collection_id, approved.clone())?;605            }606607            let list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, sender.clone()));608            if list_exists {609610                let mut list = <ApprovedList<T>>::get(collection_id, (item_id, sender.clone()));611                let item_contains = list.iter().any(|i| i.approved == approved);612613                if !item_contains {614                    list.push(ApprovePermissions { approved: approved.clone(), amount: amount });615                    <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);616                }617            } else {618619                let mut list = Vec::new();620                list.push(ApprovePermissions { approved: approved.clone(), amount: amount });621                <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);622            }623624            Ok(())625        }626627        #[weight = 0]628        pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {629630            let sender = ensure_signed(origin)?;631            let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, from.clone()));632            if approved_list_exists633            {634                Self::check_white_list(collection_id, from.clone())?;635                Self::check_white_list(collection_id, recipient.clone())?;636637                let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));638                let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());639                ensure!(opt_item.is_some(), "No approve found");640                ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved");641642                // remove approve643                let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))644                    .into_iter().filter(|i| i.approved != sender.clone()).collect();645                <ApprovedList<T>>::insert(collection_id, (item_id, from.clone()), approve_list);646            }647            else648            {649                panic!("Only approved addresses can call this method");650            }651652            let target_collection = <Collection<T>>::get(collection_id);653654            match target_collection.mode655            {656                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,657                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, from.clone(), recipient)?,658                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,659                _ => ()660            };661662            Ok(())663        }664665        #[weight = 0]666        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {667668            // let no_perm_mes = "You do not have permissions to modify this collection";669            // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);670            // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));671            // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);672673            // // on_nft_received  call674675            // Self::transfer(origin, collection_id, item_id, new_owner)?;676677            Ok(())678        }679680        #[weight = 0]681        pub fn set_offchain_schema(682            origin,683            collection_id: u64,684            schema: Vec<u8>685        ) -> DispatchResult {686            let sender = ensure_signed(origin)?;687            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;688689            let mut target_collection = <Collection<T>>::get(collection_id);690            target_collection.offchain_schema = schema;691            <Collection<T>>::insert(collection_id, target_collection);692693            Ok(())694        }695    }696}697698impl<T: Trait> Module<T> {699    fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {700        let current_index = <ItemListIndex>::get(item.collection)701            .checked_add(1)702            .expect("Item list index id error");703        let itemcopy = item.clone();704        let owner = item.owner.clone();705        let value = item.value as u64;706707        Self::add_token_index(item.collection, current_index, owner.clone())?;708709        <ItemListIndex>::insert(item.collection, current_index);710        <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);711712        // Update balance713        let new_balance = <Balance<T>>::get(item.collection, owner.clone())714            .checked_add(value)715            .unwrap();716        <Balance<T>>::insert(item.collection, owner.clone(), new_balance);717718        Ok(())719    }720721    fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {722        let current_index = <ItemListIndex>::get(item.collection)723            .checked_add(1)724            .expect("Item list index id error");725        let itemcopy = item.clone();726727        let value = item.owner.first().unwrap().fraction as u64;728        let owner = item.owner.first().unwrap().owner.clone();729730        Self::add_token_index(item.collection, current_index, owner.clone())?;731732        <ItemListIndex>::insert(item.collection, current_index);733        <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);734735        // Update balance736        let new_balance = <Balance<T>>::get(item.collection, owner.clone())737            .checked_add(value)738            .unwrap();739        <Balance<T>>::insert(item.collection, owner.clone(), new_balance);740741        Ok(())742    }743744    fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {745        let current_index = <ItemListIndex>::get(item.collection)746            .checked_add(1)747            .expect("Item list index id error");748749        let item_owner = item.owner.clone();750        let collection_id = item.collection.clone();751        Self::add_token_index(collection_id, current_index, item.owner.clone())?;752753        <ItemListIndex>::insert(collection_id, current_index);754        <NftItemList<T>>::insert(collection_id, current_index, item);755756        // Update balance757        let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())758            .checked_add(1)759            .unwrap();760        <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);761762        Ok(())763    }764765    fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {766        ensure!(767            <ReFungibleItemList<T>>::contains_key(collection_id, item_id),768            "Item does not exists"769        );770        let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);771        let item = collection772            .owner773            .iter()774            .filter(|&i| i.owner == owner)775            .next()776            .unwrap();777        Self::remove_token_index(collection_id, item_id, owner.clone())?;778779        // remove approve list780        <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));781782        // update balance783        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())784            .checked_sub(item.fraction as u64)785            .unwrap();786        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);787788        <ReFungibleItemList<T>>::remove(collection_id, item_id);789790        Ok(())791    }792793    fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {794        ensure!(795            <NftItemList<T>>::contains_key(collection_id, item_id),796            "Item does not exists"797        );798        let item = <NftItemList<T>>::get(collection_id, item_id);799        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;800801        // remove approve list802        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));803804        // update balance805        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())806            .checked_sub(1)807            .unwrap();808        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);809        <NftItemList<T>>::remove(collection_id, item_id);810811        Ok(())812    }813814    fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {815        ensure!(816            <FungibleItemList<T>>::contains_key(collection_id, item_id),817            "Item does not exists"818        );819        let item = <FungibleItemList<T>>::get(collection_id, item_id);820        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;821822        // remove approve list823        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));824825        // update balance826        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())827            .checked_sub(item.value as u64)828            .unwrap();829        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);830831        <FungibleItemList<T>>::remove(collection_id, item_id);832833        Ok(())834    }835836    fn collection_exists(collection_id: u64) -> DispatchResult {837        ensure!(838            <Collection<T>>::contains_key(collection_id),839            "This collection does not exist"840        );841        Ok(())842    }843844    fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {845        Self::collection_exists(collection_id)?;846847        let target_collection = <Collection<T>>::get(collection_id);848        ensure!(849            subject == target_collection.owner,850            "You do not own this collection"851        );852853        Ok(())854    }855856    fn is_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> bool {857858        let target_collection = <Collection<T>>::get(collection_id);859        let mut result: bool = subject == target_collection.owner;860        let exists = <AdminList<T>>::contains_key(collection_id);861862        if !result & exists {863            if <AdminList<T>>::get(collection_id).contains(&subject) {864                result = true865            }866        }867868        result869    }870871    fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {872        873        Self::collection_exists(collection_id)?;874        let result = Self::is_owner_or_admin_permissions(collection_id, subject.clone());875876        if result == true {877            Ok(())878        } else {879            panic!("You do not have permissions to modify this collection")880        }881    }882883    fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool {884        let target_collection = <Collection<T>>::get(collection_id);885886        match target_collection.mode {887            CollectionMode::NFT(_) => {888                <NftItemList<T>>::get(collection_id, item_id).owner == subject889            }890            CollectionMode::Fungible(_) => {891                <FungibleItemList<T>>::get(collection_id, item_id).owner == subject892            }893            CollectionMode::ReFungible(_, _) => {894                <ReFungibleItemList<T>>::get(collection_id, item_id)895                    .owner896                    .iter()897                    .any(|i| i.owner == subject)898            }899            CollectionMode::Invalid => false,900        }901    }902903    fn check_white_list(collection_id: u64, address: T::AccountId) -> DispatchResult {904905        let mes = "Address is not in white list";906        if <WhiteList<T>>::contains_key(collection_id){907            let wl = <WhiteList<T>>::get(collection_id);908            if !wl.contains(&address.clone()) {909                panic!(mes);910            }911        }912        else {913            panic!(mes);914        }915        Ok(())916    }917918    fn transfer_fungible(919        collection_id: u64,920        item_id: u64,921        value: u64,922        owner: T::AccountId,923        new_owner: T::AccountId,924    ) -> DispatchResult {925926        ensure!(927            <FungibleItemList<T>>::contains_key(collection_id, item_id),928            "Item not exists"929        );930931        let full_item = <FungibleItemList<T>>::get(collection_id, item_id);932        let amount = full_item.value;933934        ensure!(amount >= value.into(), "Item balance not enouth");935936        // update balance937        let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone())938            .checked_sub(value)939            .unwrap();940        <Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);941942        let mut new_owner_account_id = 0;943        let new_owner_items = <AddressTokens<T>>::get(collection_id, new_owner.clone());944        if new_owner_items.len() > 0 {945            new_owner_account_id = new_owner_items[0];946        }947948        let val64 = value.into();949950        // transfer951        if amount == val64 && new_owner_account_id == 0 {952            // change owner953            // new owner do not have account954            let mut new_full_item = full_item.clone();955            new_full_item.owner = new_owner.clone();956            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);957958            // update balance959            let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())960                .checked_add(value)961                .unwrap();962            <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);963964            // update index collection965            Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;966        } else {967            let mut new_full_item = full_item.clone();968            new_full_item.value -= val64;969970            // separate amount971            if new_owner_account_id > 0 {972                // new owner has account973                let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);974                item.value += val64;975976                // update balance977                let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())978                    .checked_add(value)979                    .unwrap();980                <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);981982                <FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);983            } else {984                // new owner do not have account985                let item = FungibleItemType {986                    collection: collection_id,987                    owner: new_owner.clone(),988                    value: val64,989                };990991                Self::add_fungible_item(item)?;992            }993994            if amount == val64 {995                Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;996997                // remove approve list998                <ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));999                <FungibleItemList<T>>::remove(collection_id, item_id);1000            }10011002            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);1003        }10041005        Ok(())1006    }10071008    fn transfer_refungible(1009        collection_id: u64,1010        item_id: u64,1011        value: u64,1012        owner: T::AccountId,1013        new_owner: T::AccountId,1014    ) -> DispatchResult {10151016        ensure!(1017            <ReFungibleItemList<T>>::contains_key(collection_id, item_id),1018            "Item not exists"1019        );10201021        let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);1022        let item = full_item1023            .owner1024            .iter()1025            .filter(|i| i.owner == owner)1026            .next()1027            .unwrap();1028        let amount = item.fraction;10291030        ensure!(amount >= value.into(), "Item balance not enouth");10311032        // update balance1033        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1034            .checked_sub(value)1035            .unwrap();1036        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);10371038        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1039            .checked_add(value)1040            .unwrap();1041        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);10421043        let old_owner = item.owner.clone();1044        let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);1045        let val64 = value.into();10461047        // transfer1048        if amount == val64 && !new_owner_has_account {1049            // change owner1050            // new owner do not have account1051            let mut new_full_item = full_item.clone();1052            new_full_item1053                .owner1054                .iter_mut()1055                .find(|i| i.owner == owner)1056                .unwrap()1057                .owner = new_owner.clone();1058            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);10591060            // update index collection1061            Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;1062        } else {1063            let mut new_full_item = full_item.clone();1064            new_full_item1065                .owner1066                .iter_mut()1067                .find(|i| i.owner == owner)1068                .unwrap()1069                .fraction -= val64;10701071            // separate amount1072            if new_owner_has_account {1073                // new owner has account1074                new_full_item1075                    .owner1076                    .iter_mut()1077                    .find(|i| i.owner == new_owner)1078                    .unwrap()1079                    .fraction += val64;1080            } else {1081                // new owner do not have account1082                new_full_item.owner.push(Ownership {1083                    owner: new_owner.clone(),1084                    fraction: val64,1085                });1086                Self::add_token_index(collection_id, item_id, new_owner.clone())?;1087            }10881089            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);1090        }10911092        Ok(())1093    }10941095    fn transfer_nft(1096        collection_id: u64,1097        item_id: u64,1098        sender: T::AccountId,1099        new_owner: T::AccountId,1100    ) -> DispatchResult {1101    1102        ensure!(1103            <NftItemList<T>>::contains_key(collection_id, item_id),1104            "Item not exists"1105        );11061107        let mut item = <NftItemList<T>>::get(collection_id, item_id);11081109        ensure!(1110            sender == item.owner,1111            "sender parameter and item owner must be equal"1112        );11131114        // update balance1115        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1116            .checked_sub(1)1117            .unwrap();1118        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);11191120        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1121            .checked_add(1)1122            .unwrap();1123        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);11241125        // change owner1126        let old_owner = item.owner.clone();1127        item.owner = new_owner.clone();1128        <NftItemList<T>>::insert(collection_id, item_id, item);11291130        // update index collection1131        Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;11321133        // reset approved list1134        <ApprovedList<T>>::remove(collection_id, (item_id, old_owner));1135        Ok(())1136    }11371138    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {1139        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1140        if list_exists {1141            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1142            let item_contains = list.contains(&item_index.clone());11431144            if !item_contains {1145                list.push(item_index.clone());1146            }11471148            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);1149        } else {1150            let mut itm = Vec::new();1151            itm.push(item_index.clone());1152            <AddressTokens<T>>::insert(collection_id, owner, itm);1153        }11541155        Ok(())1156    }11571158    fn remove_token_index(1159        collection_id: u64,1160        item_index: u64,1161        owner: T::AccountId,1162    ) -> DispatchResult {1163        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1164        if list_exists {1165            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1166            let item_contains = list.contains(&item_index.clone());11671168            if item_contains {1169                list.retain(|&item| item != item_index);1170                <AddressTokens<T>>::insert(collection_id, owner, list);1171            }1172        }11731174        Ok(())1175    }11761177    fn move_token_index(1178        collection_id: u64,1179        item_index: u64,1180        old_owner: T::AccountId,1181        new_owner: T::AccountId,1182    ) -> DispatchResult {1183        Self::remove_token_index(collection_id, item_index, old_owner)?;1184        Self::add_token_index(collection_id, item_index, new_owner)?;11851186        Ok(())1187    }1188}11891190////////////////////////////////////////////////////////////////////////////////////////////////////1191// Economic models11921193/// Fee multiplier.1194pub type Multiplier = FixedU128;11951196type BalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1197    <T as system::Trait>::AccountId,1198>>::Balance;1199type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1200    <T as system::Trait>::AccountId,1201>>::NegativeImbalance;12021203/// Require the transactor pay for themselves and maybe include a tip to gain additional priority1204/// in the queue.1205#[derive(Encode, Decode, Clone, Eq, PartialEq)]1206pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(1207    #[codec(compact)] BalanceOf<T>,1208);12091210impl<T: Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug1211    for ChargeTransactionPayment<T>1212{1213    #[cfg(feature = "std")]1214    fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1215        write!(f, "ChargeTransactionPayment<{:?}>", self.0)1216    }1217    #[cfg(not(feature = "std"))]1218    fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1219        Ok(())1220    }1221}12221223impl<T: Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T>1224where1225    T::Call:1226        Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1227    BalanceOf<T>: Send + Sync + FixedPointOperand,1228{1229    /// utility constructor. Used only in client/factory code.1230    pub fn from(fee: BalanceOf<T>) -> Self {1231        Self(fee)1232    }12331234    pub fn traditional_fee(1235        len: usize,1236        info: &DispatchInfoOf<T::Call>,1237        tip: BalanceOf<T>,1238    ) -> BalanceOf<T>1239    where1240        T::Call: Dispatchable<Info = DispatchInfo>,1241    {1242        <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)1243    }12441245    fn withdraw_fee(1246        &self,1247        who: &T::AccountId,1248        call: &T::Call,1249        info: &DispatchInfoOf<T::Call>,1250        len: usize,1251    ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {1252        let tip = self.0;12531254        // Set fee based on call type. Creating collection costs 1 Unique.1255        // All other transactions have traditional fees so far1256        let fee = match call.is_sub_type() {1257            Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1258            _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes1259                                                        // _ => <BalanceOf<T>>::from(100)1260        };12611262        // Determine who is paying transaction fee based on ecnomic model1263        // Parse call to extract collection ID and access collection sponsor1264        let sponsor: T::AccountId = match call.is_sub_type() {1265            Some(Call::create_item(collection_id, _properties, _owner)) => {1266                <Collection<T>>::get(collection_id).sponsor1267            }1268            Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {1269                <Collection<T>>::get(collection_id).sponsor1270            }12711272            _ => T::AccountId::default(),1273        };12741275        let mut who_pays_fee: T::AccountId = sponsor.clone();1276        if sponsor == T::AccountId::default() {1277            who_pays_fee = who.clone();1278        }12791280        // Only mess with balances if fee is not zero.1281        if fee.is_zero() {1282            return Ok((fee, None));1283        }12841285        match <T as transaction_payment::Trait>::Currency::withdraw(1286            &who_pays_fee,1287            fee,1288            if tip.is_zero() {1289                WithdrawReason::TransactionPayment.into()1290            } else {1291                WithdrawReason::TransactionPayment | WithdrawReason::Tip1292            },1293            ExistenceRequirement::KeepAlive,1294        ) {1295            Ok(imbalance) => Ok((fee, Some(imbalance))),1296            Err(_) => Err(InvalidTransaction::Payment.into()),1297        }1298    }1299}13001301impl<T: Trait + transaction_payment::Trait + Send + Sync> SignedExtension1302    for ChargeTransactionPayment<T>1303where1304    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,1305    T::Call:1306        Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1307{1308    const IDENTIFIER: &'static str = "ChargeTransactionPayment";1309    type AccountId = T::AccountId;1310    type Call = T::Call;1311    type AdditionalSigned = ();1312    type Pre = (1313        BalanceOf<T>,1314        Self::AccountId,1315        Option<NegativeImbalanceOf<T>>,1316        BalanceOf<T>,1317    );1318    fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {1319        Ok(())1320    }13211322    fn validate(1323        &self,1324        who: &Self::AccountId,1325        call: &Self::Call,1326        info: &DispatchInfoOf<Self::Call>,1327        len: usize,1328    ) -> TransactionValidity {1329        let (fee, _) = self.withdraw_fee(who, call, info, len)?;13301331        let mut r = ValidTransaction::default();1332        // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which1333        // will be a bit more than setting the priority to tip. For now, this is enough.1334        r.priority = fee.saturated_into::<TransactionPriority>();1335        Ok(r)1336    }13371338    fn pre_dispatch(1339        self,1340        who: &Self::AccountId,1341        call: &Self::Call,1342        info: &DispatchInfoOf<Self::Call>,1343        len: usize,1344    ) -> Result<Self::Pre, TransactionValidityError> {1345        let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;1346        Ok((self.0, who.clone(), imbalance, fee))1347    }13481349    fn post_dispatch(1350        pre: Self::Pre,1351        info: &DispatchInfoOf<Self::Call>,1352        post_info: &PostDispatchInfoOf<Self::Call>,1353        len: usize,1354        _result: &DispatchResult,1355    ) -> Result<(), TransactionValidityError> {1356        let (tip, who, imbalance, fee) = pre;1357        if let Some(payed) = imbalance {1358            let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(1359                len as u32, info, post_info, tip,1360            );1361            let refund = fee.saturating_sub(actual_fee);1362            let actual_payment =1363                match <T as transaction_payment::Trait>::Currency::deposit_into_existing(1364                    &who, refund,1365                ) {1366                    Ok(refund_imbalance) => {1367                        // The refund cannot be larger than the up front payed max weight.1368                        // `PostDispatchInfo::calc_unspent` guards against such a case.1369                        match payed.offset(refund_imbalance) {1370                            Ok(actual_payment) => actual_payment,1371                            Err(_) => return Err(InvalidTransaction::Payment.into()),1372                        }1373                    }1374                    // We do not recreate the account using the refund. The up front payment1375                    // is gone in that case.1376                    Err(_) => payed,1377                };1378            let imbalances = actual_payment.split(tip);1379            <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(1380                Some(imbalances.0).into_iter().chain(Some(imbalances.1)),1381            );1382        }1383        Ok(())1384    }1385}