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

difftreelog

Code style update

str-mv2020-09-09parent: #d96245d.patch.diff
in: master

9 files changed

modifiednode/src/cli.rsdiffbeforeafterboth
--- a/node/src/cli.rs
+++ b/node/src/cli.rs
@@ -3,9 +3,9 @@
 
 #[derive(Debug, StructOpt)]
 pub struct Cli {
-	#[structopt(subcommand)]
-	pub subcommand: Option<Subcommand>,
+    #[structopt(subcommand)]
+    pub subcommand: Option<Subcommand>,
 
-	#[structopt(flatten)]
-	pub run: RunCmd,
+    #[structopt(flatten)]
+    pub run: RunCmd,
 }
modifiednode/src/command.rsdiffbeforeafterboth
--- a/node/src/command.rs
+++ b/node/src/command.rs
@@ -21,61 +21,57 @@
 use sc_cli::SubstrateCli;
 
 impl SubstrateCli for Cli {
-	fn impl_name() -> &'static str {
-		"Substrate Node"
-	}
+    fn impl_name() -> &'static str {
+        "Substrate Node"
+    }
 
-	fn impl_version() -> &'static str {
-		env!("SUBSTRATE_CLI_IMPL_VERSION")
-	}
+    fn impl_version() -> &'static str {
+        env!("SUBSTRATE_CLI_IMPL_VERSION")
+    }
 
-	fn description() -> &'static str {
-		env!("CARGO_PKG_DESCRIPTION")
-	}
+    fn description() -> &'static str {
+        env!("CARGO_PKG_DESCRIPTION")
+    }
 
-	fn author() -> &'static str {
-		env!("CARGO_PKG_AUTHORS")
-	}
+    fn author() -> &'static str {
+        env!("CARGO_PKG_AUTHORS")
+    }
 
-	fn support_url() -> &'static str {
-		"support.anonymous.an"
-	}
+    fn support_url() -> &'static str {
+        "support.anonymous.an"
+    }
 
-	fn copyright_start_year() -> i32 {
-		2017
-	}
+    fn copyright_start_year() -> i32 {
+        2017
+    }
 
-	fn executable_name() -> &'static str {
-		env!("CARGO_PKG_NAME")
-	}
+    fn executable_name() -> &'static str {
+        env!("CARGO_PKG_NAME")
+    }
 
-	fn load_spec(&self, id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> {
-		Ok(match id {
-			"dev" => Box::new(chain_spec::development_config()),
-			"" | "local" => Box::new(chain_spec::local_testnet_config()),
-			path => Box::new(chain_spec::ChainSpec::from_json_file(
-				std::path::PathBuf::from(path),
-			)?),
-		})
-	}
+    fn load_spec(&self, id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> {
+        Ok(match id {
+            "dev" => Box::new(chain_spec::development_config()),
+            "" | "local" => Box::new(chain_spec::local_testnet_config()),
+            path => Box::new(chain_spec::ChainSpec::from_json_file(
+                std::path::PathBuf::from(path),
+            )?),
+        })
+    }
 }
 
 /// Parse and run command line arguments
 pub fn run() -> sc_cli::Result<()> {
-	let cli = Cli::from_args();
+    let cli = Cli::from_args();
 
-	match &cli.subcommand {
-		Some(subcommand) => {
-			let runner = cli.create_runner(subcommand)?;
-			runner.run_subcommand(subcommand, |config| Ok(new_full_start!(config).0))
-		}
-		None => {
-			let runner = cli.create_runner(&cli.run)?;
-			runner.run_node(
-				service::new_light,
-				service::new_full,
-				nft_runtime::VERSION
-			)
-		}
-	}
-}
\ No newline at end of file
+    match &cli.subcommand {
+        Some(subcommand) => {
+            let runner = cli.create_runner(subcommand)?;
+            runner.run_subcommand(subcommand, |config| Ok(new_full_start!(config).0))
+        }
+        None => {
+            let runner = cli.create_runner(&cli.run)?;
+            runner.run_node(service::new_light, service::new_full, nft_runtime::VERSION)
+        }
+    }
+}
modifiednode/src/main.rsdiffbeforeafterboth
--- a/node/src/main.rs
+++ b/node/src/main.rs
@@ -8,5 +8,5 @@
 mod command;
 
 fn main() -> sc_cli::Result<()> {
-	command::run()
+    command::run()
 }
modifiednode/src/service.rsdiffbeforeafterboth
--- a/node/src/service.rs
+++ b/node/src/service.rs
@@ -188,7 +188,7 @@
             prometheus_registry: service.prometheus_registry(),
             shared_voter_state: SharedVoterState::empty(),
         };
-        
+
         // the GRANDPA voter task is considered infallible, i.e.
         // if it fails we take down the service with it.
         service.spawn_essential_task_handle().spawn_blocking(
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
before · pallets/nft/src/lib.rs
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.rs56use codec::{Decode, Encode};7pub use frame_support::{8    decl_event, decl_module, decl_storage,9    construct_runtime, parameter_types,10    traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason, Imbalance},11    weights::{12        DispatchInfo, PostDispatchInfo, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},13        IdentityFee, Weight, WeightToFeePolynomial, GetDispatchInfo, Pays,14    },15    StorageValue,16    dispatch::DispatchResult, 17    IsSubType,18    ensure19};2021use frame_system::{self as system, ensure_signed};22use sp_runtime::sp_std::prelude::Vec;23use sp_std::prelude::*;24use sp_runtime::{25	FixedU128, FixedPointOperand, 26	transaction_validity::{27		TransactionPriority, ValidTransaction, InvalidTransaction, TransactionValidityError, TransactionValidity28	},29	traits::{30        Saturating, Dispatchable, DispatchInfoOf, PostDispatchInfoOf, SignedExtension, Zero, SaturatedConversion,31	},32};3334#[cfg(test)]35mod mock;3637#[cfg(test)]38mod tests;3940#[derive(Encode, Decode, Debug, Eq, Clone, PartialEq)]41pub enum CollectionMode {42    Invalid,43    // custom data size44    NFT(u32),45    // decimal points46    Fungible(u32),47    // custom data size and decimal points48	ReFungible(u32, u32),49}5051impl Into<u8> for CollectionMode {52    fn into(self) -> u8{53        match self {54            CollectionMode::Invalid => 0,55            CollectionMode::NFT(_) => 1,56            CollectionMode::Fungible(_) => 2,57            CollectionMode::ReFungible(_, _) => 3,58        }59    }60}6162#[derive(Encode, Decode, Debug, Clone, PartialEq)]63pub enum AccessMode {64    Normal,65	WhiteList,66}67impl Default for AccessMode { fn default() -> Self { Self::Normal } }6869impl Default for CollectionMode { fn default() -> Self { Self::Invalid } }7071#[derive(Encode, Decode, Default, Clone, PartialEq)]72#[cfg_attr(feature = "std", derive(Debug))]73pub struct Ownership<AccountId> {74    pub owner: AccountId,75    pub fraction: u12876}7778#[derive(Encode, Decode, Default, Clone, PartialEq)]79#[cfg_attr(feature = "std", derive(Debug))]80pub struct CollectionType<AccountId> {81    pub owner: AccountId,82    pub mode: CollectionMode,83    pub access: AccessMode,84    pub decimal_points: u32,85    pub name: Vec<u16>,        // 64 include null escape char86    pub description: Vec<u16>, // 256 include null escape char87    pub token_prefix: Vec<u8>, // 16 include null escape char88    pub custom_data_size: u32,89    pub offchain_schema: Vec<u8>,90    pub sponsor: AccountId,    // Who pays fees. If set to default address, the fees are applied to the transaction sender91    pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship92}9394#[derive(Encode, Decode, Default, Clone, PartialEq)]95#[cfg_attr(feature = "std", derive(Debug))]96pub struct CollectionAdminsType<AccountId> {97    pub admin: AccountId,98    pub collection_id: u64,99}100101#[derive(Encode, Decode, Default, Clone, PartialEq)]102#[cfg_attr(feature = "std", derive(Debug))]103pub struct NftItemType<AccountId> {104    pub collection: u64,105    pub owner: AccountId,106    pub data: Vec<u8>,107}108109#[derive(Encode, Decode, Default, Clone, PartialEq)]110#[cfg_attr(feature = "std", derive(Debug))]111pub struct FungibleItemType<AccountId> {112    pub collection: u64,113    pub owner: AccountId,114    pub value: u128,115}116117#[derive(Encode, Decode, Default, Clone, PartialEq)]118#[cfg_attr(feature = "std", derive(Debug))]119pub struct ReFungibleItemType<AccountId> {120    pub collection: u64,121    pub owner: Vec<Ownership<AccountId>>,122    pub data: Vec<u8>,123}124125#[derive(Encode, Decode, Default, Clone, PartialEq)]126#[cfg_attr(feature = "std", derive(Debug))]127pub struct ApprovePermissions<AccountId> {128    pub approved: AccountId,129    pub amount: u64130}131132#[derive(Encode, Decode, Default, Clone, PartialEq)]133#[cfg_attr(feature = "std", derive(Debug))]134pub struct VestingItem<AccountId, Moment>135{136    pub sender: AccountId,137    pub recipient: AccountId,138    pub collection_id: u64,139    pub item_id: u64,140    pub amount: u64,141    pub vesting_date: Moment142}143144pub trait Trait: system::Trait {145    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;146147}148149decl_storage! {150    trait Store for Module<T: Trait> as Nft {151152        // Private members153        NextCollectionID: u64;154        ItemListIndex: map hasher(blake2_128_concat) u64 => u64;155156        pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;157        pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;158        pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;159160        /// Balance owner per collection map161        pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;162163        /// second parameter: item id + owner account id164        pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) (u64, T::AccountId) => Vec<ApprovePermissions<T::AccountId>>;165166        /// Item collections167        pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;168        pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;169        pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;170171        // Active vesting list172        // pub VestingList get(fn vesting): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => VestingItem<T::AccountId, T::Moment>;173174        /// Index list175        pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;176177        // Sponsorship178        pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;179        pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;180    }181}182183decl_event!(184    pub enum Event<T>185    where186        AccountId = <T as system::Trait>::AccountId,187    {188        Created(u64, u8, AccountId),189        ItemCreated(u64, u64),190        ItemDestroyed(u64, u64),191    }192);193194decl_module! {195    pub struct Module<T: Trait> for enum Call where origin: T::Origin {196197        fn deposit_event() = default;198199        // Create collection of NFT with given parameters200        //201        // @param customDataSz size of custom data in each collection item202        // returns collection ID203        #[weight = 0]204        pub fn create_collection(   origin,205                                    collection_name: Vec<u16>,206                                    collection_description: Vec<u16>,207                                    token_prefix: Vec<u8>,208                                    mode: CollectionMode) -> DispatchResult {209210            // Anyone can create a collection211            let who = ensure_signed(origin)?;212            let custom_data_size = match mode {213                CollectionMode::NFT(size) => size,214                CollectionMode::ReFungible(size, _) => size,215                _ => 0216            };217218            let decimal_points = match mode {219                CollectionMode::Fungible(points) => points,220                CollectionMode::ReFungible(_, points) => points,221                _ => 0222            };223224            // check params225            ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4"); 226227            let mut name = collection_name.to_vec();228            name.push(0);229            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");230231            let mut description = collection_description.to_vec();232            description.push(0);233            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");234235            let mut prefix = token_prefix.to_vec();236            prefix.push(0);237            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");238239            // Generate next collection ID240            let next_id = NextCollectionID::get()241                .checked_add(1)242                .expect("collection id error");243244            NextCollectionID::put(next_id);245246            // Create new collection247            let new_collection = CollectionType {248                owner: who.clone(),249                name: name,250                mode: mode.clone(),251                access: AccessMode::Normal,252                description: description,253                decimal_points: decimal_points,254                token_prefix: prefix,255                offchain_schema: Vec::new(),256                custom_data_size: custom_data_size,257                sponsor: T::AccountId::default(),258                unconfirmed_sponsor: T::AccountId::default(),259            };260261            // Add new collection to map262            <Collection<T>>::insert(next_id, new_collection);263264            // call event265            Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));266267            Ok(())268        }269270        #[weight = 0]271        pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {272273            let sender = ensure_signed(origin)?;274            Self::check_owner_permissions(collection_id, sender)?;275276            // TODO Items remove277            <AddressTokens<T>>::remove_prefix(collection_id);278            <ApprovedList<T>>::remove_prefix(collection_id);279            <Balance<T>>::remove_prefix(collection_id);280            <ItemListIndex>::remove(collection_id);281            <AdminList<T>>::remove(collection_id);282            <Collection<T>>::remove(collection_id);283            <WhiteList<T>>::remove(collection_id);284285            Ok(())286        }287288        #[weight = 0]289        pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {290291            let sender = ensure_signed(origin)?;292            Self::check_owner_permissions(collection_id, sender)?;293            let mut target_collection = <Collection<T>>::get(collection_id);294            target_collection.owner = new_owner;295            <Collection<T>>::insert(collection_id, target_collection);296297            Ok(())298        }299300        #[weight = 0]301        pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {302303            let sender = ensure_signed(origin)?;304            Self::check_owner_or_admin_permissions(collection_id, sender)?;305            let mut admin_arr: Vec<T::AccountId> = Vec::new();306307            if <AdminList<T>>::contains_key(collection_id)308            {309                admin_arr = <AdminList<T>>::get(collection_id);310                ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");311            }312313            admin_arr.push(new_admin_id);314            <AdminList<T>>::insert(collection_id, admin_arr);315316            Ok(())317        }318319        #[weight = 0]320        pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {321322            let sender = ensure_signed(origin)?;323            Self::check_owner_or_admin_permissions(collection_id, sender)?;324325            if <AdminList<T>>::contains_key(collection_id)326            {327                let mut admin_arr = <AdminList<T>>::get(collection_id);328                admin_arr.retain(|i| *i != account_id);329                <AdminList<T>>::insert(collection_id, admin_arr);330            }331332            Ok(())333        }334335        #[weight = 0]336        pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {337338            let sender = ensure_signed(origin)?;339            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");340341            let mut target_collection = <Collection<T>>::get(collection_id);342            ensure!(sender == target_collection.owner, "You do not own this collection");343344            target_collection.unconfirmed_sponsor = new_sponsor;345            <Collection<T>>::insert(collection_id, target_collection);346347            Ok(())348        }349350        #[weight = 0]351        pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {352353            let sender = ensure_signed(origin)?;354            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");355356            let mut target_collection = <Collection<T>>::get(collection_id);357            ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");358359            target_collection.sponsor = target_collection.unconfirmed_sponsor;360            target_collection.unconfirmed_sponsor = T::AccountId::default();361            <Collection<T>>::insert(collection_id, target_collection);362363            Ok(())364        }365366        #[weight = 0]367        pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {368369            let sender = ensure_signed(origin)?;370            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");371372            let mut target_collection = <Collection<T>>::get(collection_id);373            ensure!(sender == target_collection.owner, "You do not own this collection");374375            target_collection.sponsor = T::AccountId::default();376            <Collection<T>>::insert(collection_id, target_collection);377378            Ok(())379        }380        381        #[weight = 0]382        pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {383384            let sender = ensure_signed(origin)?;385            let target_collection = <Collection<T>>::get(collection_id);386            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;387388            // TODO: implement other modes389            match target_collection.mode 390            {391                CollectionMode::NFT(_) => {392393                    // check size394                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");395396                    // Create nft item397                    let item = NftItemType {398                        collection: collection_id,399                        owner: owner,400                        data: properties,401                    };402    403                    Self::add_nft_item(item)?;404    405                },406                CollectionMode::Fungible(_) => {407408                    // check size409                    ensure!(properties.len() as u32 == 0, "Size of item must be 0 with fungible type");410411                    let item = FungibleItemType {412                        collection: collection_id,413                        owner: owner,414                        value: (10 as u128).pow(target_collection.decimal_points)415                    };416    417                    Self::add_fungible_item(item)?;418                },419                CollectionMode::ReFungible(_, _) => {420421                    // check size422                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");423424                    let mut owner_list = Vec::new();425                    let value = (10 as u128).pow(target_collection.decimal_points);426                    owner_list.push(Ownership {owner: owner, fraction: value});427428                    let item = ReFungibleItemType {429                        collection: collection_id,430                        owner: owner_list,431                        data: properties432                    };433    434                    Self::add_refungible_item(item)?;435                },436                _ => ()437            };438439            // call event440            Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));441442            Ok(())443        }444445        #[weight = 0]446        pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {447448            let sender = ensure_signed(origin)?;449            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);450            if !item_owner451            {452                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;453            }454            let target_collection = <Collection<T>>::get(collection_id);455456            match target_collection.mode 457            {458                CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,459                CollectionMode::Fungible(_)  => Self::burn_fungible_item(collection_id, item_id)?,460                CollectionMode::ReFungible(_, _)  => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,461                _ => ()462            };463464            // call event465            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));466467            Ok(())468        }469470        #[weight = 0]471        pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {472473            let sender = ensure_signed(origin)?;474            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");475476            let target_collection = <Collection<T>>::get(collection_id);477478            // TODO: implement other modes479            match target_collection.mode 480            {481                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,482                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,483                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,484                _ => ()485            };486487            Ok(())488        }489490        #[weight = 0]491        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {492493            let sender = ensure_signed(origin)?;494495            // amount param stub496            let amount = 100000000;497498            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");499500            let list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, sender.clone()));501            if list_exists {502503                let mut list = <ApprovedList<T>>::get(collection_id, (item_id, sender.clone()));504                let item_contains = list.iter().any(|i| i.approved == approved);505506                if !item_contains {507                    list.push(ApprovePermissions { approved: approved.clone(), amount: amount });508                    <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);509                }510            } else {511512                let mut list = Vec::new();513                list.push(ApprovePermissions { approved: approved.clone(), amount: amount });514                <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);515            }516517            Ok(())518        }519520        #[weight = 0]521        pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {522523            let sender = ensure_signed(origin)?;524            let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, from.clone()));525            if approved_list_exists526            {527                let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));528                let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());529                ensure!(opt_item.is_some(), "No approve found"); 530                ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved"); 531532                // remove approve533                let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))534                    .into_iter().filter(|i| i.approved != sender.clone()).collect();535                <ApprovedList<T>>::insert(collection_id, (item_id, from.clone()), approve_list);536            }537            else538            {539                Self::check_owner_or_admin_permissions(collection_id, sender)?;540            }541            542            let target_collection = <Collection<T>>::get(collection_id);543544            match target_collection.mode545            {546                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,547                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, from.clone(), recipient)?,548                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,549                _ => ()550            };551552            Ok(())553        }554555        #[weight = 0]556        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {557558            // let no_perm_mes = "You do not have permissions to modify this collection";559            // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);560            // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));561            // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);562563            // // on_nft_received  call564565            // Self::transfer(origin, collection_id, item_id, new_owner)?;566567            Ok(())568        }569570        #[weight = 0]571        pub fn set_offchain_schema(572            origin,573            collection_id: u64,574            schema: Vec<u8>575        ) -> DispatchResult {576            let sender = ensure_signed(origin)?;577            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;578            579            let mut target_collection = <Collection<T>>::get(collection_id);580            target_collection.offchain_schema = schema;581            <Collection<T>>::insert(collection_id, target_collection);582583            Ok(())        584        }585    }586}587588impl<T: Trait> Module<T> {589590    fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {591592        let current_index = <ItemListIndex>::get(item.collection)593        .checked_add(1)594        .expect("Item list index id error");595        let itemcopy = item.clone();596        let owner = item.owner.clone();597        let value = item.value as u64;598599        Self::add_token_index(item.collection, current_index, owner.clone())?;600601        <ItemListIndex>::insert(item.collection, current_index);602        <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);  603        604        // Update balance605       let new_balance = <Balance<T>>::get(item.collection, owner.clone()).checked_add(value).unwrap();606       <Balance<T>>::insert(item.collection, owner.clone(), new_balance);607608        Ok(())609    }610611    fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {612613        let current_index = <ItemListIndex>::get(item.collection)614        .checked_add(1)615        .expect("Item list index id error");616        let itemcopy = item.clone();617618        let value = item.owner.first().unwrap().fraction as u64;619        let owner = item.owner.first().unwrap().owner.clone();620621        Self::add_token_index(item.collection, current_index, owner.clone())?;622623        <ItemListIndex>::insert(item.collection, current_index);624        <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);  625        626        // Update balance627       let new_balance = <Balance<T>>::get(item.collection, owner.clone()).checked_add(value).unwrap();628       <Balance<T>>::insert(item.collection, owner.clone(), new_balance);629630        Ok(())631    }632633    fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {634635        let current_index = <ItemListIndex>::get(item.collection)636        .checked_add(1)637        .expect("Item list index id error");638639        let item_owner = item.owner.clone();640        let collection_id = item.collection.clone();641        Self::add_token_index(collection_id, current_index, item.owner.clone())?;642643        <ItemListIndex>::insert(collection_id, current_index);644        <NftItemList<T>>::insert(collection_id, current_index, item);645646        // Update balance647        let new_balance = <Balance<T>>::get(collection_id, item_owner.clone()).checked_add(1).unwrap();648        <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);649650        Ok(())651    }652653    fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {654  655        ensure!(<ReFungibleItemList<T>>::contains_key(collection_id, item_id), "Item does not exists");656        let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);657        let item = collection.owner.iter().filter(|&i| i.owner == owner).next().unwrap();658        Self::remove_token_index(collection_id, item_id, owner.clone())?;659660        // remove approve list661        <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));662663        // update balance664        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(item.fraction as u64).unwrap();665        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);666667668        <ReFungibleItemList<T>>::remove(collection_id, item_id);669670        Ok(())671    }672673    fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {674  675        ensure!(<NftItemList<T>>::contains_key(collection_id, item_id), "Item does not exists");676        let item = <NftItemList<T>>::get(collection_id, item_id);677        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;678679        // remove approve list680        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));681682        // update balance683        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();684        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);685        <NftItemList<T>>::remove(collection_id, item_id);686687        Ok(())688    }689690    fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {691  692        ensure!(<FungibleItemList<T>>::contains_key(collection_id, item_id), "Item does not exists");693        let item = <FungibleItemList<T>>::get(collection_id, item_id);694        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;695696        // remove approve list697        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));698699        // update balance700        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(item.value as u64).unwrap();701        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);702703        <FungibleItemList<T>>::remove(collection_id, item_id);704705        Ok(())        706    }707708    fn collection_exists(collection_id: u64) -> DispatchResult{709        ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");710        Ok(())711    }712713    fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {714715        Self::collection_exists(collection_id)?;716717        let target_collection = <Collection<T>>::get(collection_id);718        ensure!(subject == target_collection.owner, "You do not own this collection");719720        Ok(())721    }722723    fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {724725        Self::collection_exists(collection_id)?;726727        let target_collection = <Collection<T>>::get(collection_id);728        let is_owner = subject == target_collection.owner;729730        let no_perm_mes = "You do not have permissions to modify this collection";731        let exists = <AdminList<T>>::contains_key(collection_id);732733        if !is_owner734        {735            ensure!(exists, no_perm_mes);736            ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);737        }738        Ok(())739    }740741    fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{742743        let target_collection = <Collection<T>>::get(collection_id);744745        match target_collection.mode {746            CollectionMode::NFT(_) => <NftItemList<T>>::get(collection_id, item_id).owner == subject,747            CollectionMode::Fungible(_) => <FungibleItemList<T>>::get(collection_id, item_id).owner == subject,748            CollectionMode::ReFungible(_, _)  => <ReFungibleItemList<T>>::get(collection_id, item_id).owner.iter().any(|i| i.owner == subject),749            CollectionMode::Invalid => false750        }751    }752753    fn transfer_fungible(collection_id: u64, item_id: u64, value: u64, owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {754        let full_item = <FungibleItemList<T>>::get(collection_id, item_id);755        let amount = full_item.value;756757        ensure!(amount >= value.into(),"Item balance not enouth");758759        // update balance760        let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone()).checked_sub(value).unwrap();761        <Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);762763        let mut new_owner_account_id = 0;764        let new_owner_items = <AddressTokens<T>>::get(collection_id, new_owner.clone());765        if new_owner_items.len() > 0 {766            new_owner_account_id = new_owner_items[0];767        }768769        let val64 = value.into();770771        // transfer772        if amount == val64 && new_owner_account_id == 0773        {774            // change owner775            // new owner do not have account776            let mut new_full_item = full_item.clone();777            new_full_item.owner = new_owner.clone();778            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);779780            // update balance781            let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();782            <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);783784            // update index collection785            Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;786        }787        else788        {789            let mut new_full_item = full_item.clone();790            new_full_item.value -= val64;791792            // separate amount793            if new_owner_account_id > 0 {794795                // new owner has account796                let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);797                item.value += val64;798799                // update balance800                let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();801                <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);802803                <FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);804            }805            else806            {807                // new owner do not have account808                let item = FungibleItemType {809                    collection: collection_id,810                    owner: new_owner.clone(),811                    value: val64812                };813814                Self::add_fungible_item(item)?;815            }816817            if amount == val64{818                Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;819        820                // remove approve list821                <ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));822                <FungibleItemList<T>>::remove(collection_id, item_id);823            }824825            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);826        }827828        Ok(())829    }830831    fn transfer_refungible(collection_id: u64, item_id: u64, value: u64, owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {832        let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);833        let item = full_item.owner.iter().filter(|i| i.owner == owner).next().unwrap();834        let amount = item.fraction;835836        ensure!(amount >= value.into(),"Item balance not enouth");837838        // update balance839        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(value).unwrap();840        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);841842        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();843        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);844845        let old_owner = item.owner.clone();846        let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);847        let val64 = value.into();848849        // transfer850        if amount == val64 && !new_owner_has_account851        {852            // change owner853            // new owner do not have account854            let mut new_full_item = full_item.clone();855            new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().owner = new_owner.clone();856            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);857858            // update index collection859            Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;860        }861        else862        {863            let mut new_full_item = full_item.clone();864            new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().fraction -= val64;865866            // separate amount867            if new_owner_has_account {868                // new owner has account869                new_full_item.owner.iter_mut().find(|i| i.owner == new_owner).unwrap().fraction += val64;870            }871            else872            {873                // new owner do not have account874                new_full_item.owner.push(Ownership { owner: new_owner.clone(), fraction: val64});875                Self::add_token_index(collection_id, item_id, new_owner.clone())?;876            }877878            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);879        }880881        Ok(())882    }883884    fn transfer_nft(collection_id: u64, item_id: u64, sender: T::AccountId, new_owner: T::AccountId) -> DispatchResult {885886        let mut item = <NftItemList<T>>::get(collection_id, item_id);887888        ensure!(sender == item.owner,"sender parameter and item owner must be equal");889890        // update balance891        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();892        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);893894        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();895        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);896897        // change owner898        let old_owner = item.owner.clone();899        item.owner = new_owner.clone();900        <NftItemList<T>>::insert(collection_id, item_id, item);901902        // update index collection903        Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;904905        // reset approved list906        <ApprovedList<T>>::remove(collection_id, (item_id, old_owner));907        Ok(())908    }909910    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {911        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());912        if list_exists {913            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());914            let item_contains = list.contains(&item_index.clone());915916            if !item_contains {917                list.push(item_index.clone());918            }919920            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);921        } else {922            let mut itm = Vec::new();923            itm.push(item_index.clone());924            <AddressTokens<T>>::insert(collection_id, owner, itm);925        }926927        Ok(())928    }929930    fn remove_token_index(931        collection_id: u64,932        item_index: u64,933        owner: T::AccountId,934    ) -> DispatchResult {935        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());936        if list_exists {937            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());938            let item_contains = list.contains(&item_index.clone());939940            if item_contains {941                list.retain(|&item| item != item_index);942                <AddressTokens<T>>::insert(collection_id, owner, list);943            }944        }945946        Ok(())947    }948949    fn move_token_index(950        collection_id: u64,951        item_index: u64,952        old_owner: T::AccountId,953        new_owner: T::AccountId,954    ) -> DispatchResult {955        Self::remove_token_index(collection_id, item_index, old_owner)?;956        Self::add_token_index(collection_id, item_index, new_owner)?;957958        Ok(())959    }960}961962963////////////////////////////////////////////////////////////////////////////////////////////////////964// Economic models965966/// Fee multiplier.967pub type Multiplier = FixedU128;968969type BalanceOf<T> =970	<<T as transaction_payment::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;971type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<972	<T as system::Trait>::AccountId,>>::NegativeImbalance;973974975976/// Require the transactor pay for themselves and maybe include a tip to gain additional priority977/// in the queue.978#[derive(Encode, Decode, Clone, Eq, PartialEq)]979pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(#[codec(compact)] BalanceOf<T>);980981impl<T:Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug for ChargeTransactionPayment<T> {982	#[cfg(feature = "std")]983	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {984		write!(f, "ChargeTransactionPayment<{:?}>", self.0)985	}986	#[cfg(not(feature = "std"))]987	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {988		Ok(())989	}990}991992impl<T:Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T> where993	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,994	BalanceOf<T>: Send + Sync + FixedPointOperand,995{996	/// utility constructor. Used only in client/factory code.997	pub fn from(fee: BalanceOf<T>) -> Self {998		Self(fee)999	}10001001    pub fn traditional_fee(1002        len: usize,1003        info: &DispatchInfoOf<T::Call>,1004        tip: BalanceOf<T>,1005    ) -> BalanceOf<T> where1006        T::Call: Dispatchable<Info=DispatchInfo>,1007    {1008        <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)1009    }10101011	fn withdraw_fee(1012		&self,1013        who: &T::AccountId,1014        call: &T::Call,1015		info: &DispatchInfoOf<T::Call>,1016		len: usize,1017	) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {1018        let tip = self.0;10191020        // Set fee based on call type. Creating collection costs 1 Unique.1021        // All other transactions have traditional fees so far1022        let fee = match call.is_sub_type() {1023            Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1024            _ => Self::traditional_fee(len, info, tip)10251026            // Flat fee model, use only for testing purposes1027            // _ => <BalanceOf<T>>::from(100)1028        };10291030        // Determine who is paying transaction fee based on ecnomic model1031        // Parse call to extract collection ID and access collection sponsor1032        let sponsor: T::AccountId = match call.is_sub_type() {1033            Some(Call::create_item(collection_id, _properties, _owner)) => {1034                <Collection<T>>::get(collection_id).sponsor1035            },1036            Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {1037                <Collection<T>>::get(collection_id).sponsor1038            },10391040            _ => T::AccountId::default()1041        };10421043        let mut who_pays_fee: T::AccountId = sponsor.clone();1044        if sponsor == T::AccountId::default() {1045            who_pays_fee = who.clone();1046        }10471048		// Only mess with balances if fee is not zero.1049		if fee.is_zero() {1050			return Ok((fee, None));1051		}10521053		match <T as transaction_payment::Trait>::Currency::withdraw(1054			&who_pays_fee,1055			fee,1056			if tip.is_zero() {1057				WithdrawReason::TransactionPayment.into()1058			} else {1059				WithdrawReason::TransactionPayment | WithdrawReason::Tip1060			},1061			ExistenceRequirement::KeepAlive,1062		) {1063			Ok(imbalance) => Ok((fee, Some(imbalance))),1064			Err(_) => Err(InvalidTransaction::Payment.into()),1065		}1066	}1067}10681069impl<T:Trait + transaction_payment::Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> where1070    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,1071    T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,1072{1073	const IDENTIFIER: &'static str = "ChargeTransactionPayment";1074	type AccountId = T::AccountId;1075	type Call = T::Call;1076	type AdditionalSigned = ();1077	type Pre = (BalanceOf<T>, Self::AccountId, Option<NegativeImbalanceOf<T>>, BalanceOf<T>);1078	fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { Ok(()) }10791080	fn validate(1081		&self,1082		who: &Self::AccountId,1083		call: &Self::Call,1084		info: &DispatchInfoOf<Self::Call>,1085		len: usize,1086	) -> TransactionValidity {1087		let (fee, _) = self.withdraw_fee(who, call, info, len)?;10881089		let mut r = ValidTransaction::default();1090		// NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which1091		// will be a bit more than setting the priority to tip. For now, this is enough.1092		r.priority = fee.saturated_into::<TransactionPriority>();1093		Ok(r)1094	}10951096	fn pre_dispatch(1097		self,1098		who: &Self::AccountId,1099		call: &Self::Call,1100		info: &DispatchInfoOf<Self::Call>,1101		len: usize1102	) -> Result<Self::Pre, TransactionValidityError> {1103		let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;1104		Ok((self.0, who.clone(), imbalance, fee))1105	}11061107	fn post_dispatch(1108		pre: Self::Pre,1109		info: &DispatchInfoOf<Self::Call>,1110		post_info: &PostDispatchInfoOf<Self::Call>,1111		len: usize,1112		_result: &DispatchResult,1113	) -> Result<(), TransactionValidityError> {1114		let (tip, who, imbalance, fee) = pre;1115		if let Some(payed) = imbalance {1116			let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(1117				len as u32,1118				info,1119				post_info,1120				tip,1121			);1122			let refund = fee.saturating_sub(actual_fee);1123			let actual_payment = match <T as transaction_payment::Trait>::Currency::deposit_into_existing(&who, refund) {1124				Ok(refund_imbalance) => {1125					// The refund cannot be larger than the up front payed max weight.1126					// `PostDispatchInfo::calc_unspent` guards against such a case.1127					match payed.offset(refund_imbalance) {1128						Ok(actual_payment) => actual_payment,1129						Err(_) => return Err(InvalidTransaction::Payment.into()),1130					}1131				}1132				// We do not recreate the account using the refund. The up front payment1133				// is gone in that case.1134				Err(_) => payed,1135			};1136			let imbalances = actual_payment.split(tip);1137			<T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(Some(imbalances.0).into_iter()1138				.chain(Some(imbalances.1)));1139		}1140		Ok(())1141	}1142}
after · pallets/nft/src/lib.rs
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 offchain_schema: Vec<u8>,101    pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender102    pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship103}104105#[derive(Encode, Decode, Default, Clone, PartialEq)]106#[cfg_attr(feature = "std", derive(Debug))]107pub struct CollectionAdminsType<AccountId> {108    pub admin: AccountId,109    pub collection_id: u64,110}111112#[derive(Encode, Decode, Default, Clone, PartialEq)]113#[cfg_attr(feature = "std", derive(Debug))]114pub struct NftItemType<AccountId> {115    pub collection: u64,116    pub owner: AccountId,117    pub data: Vec<u8>,118}119120#[derive(Encode, Decode, Default, Clone, PartialEq)]121#[cfg_attr(feature = "std", derive(Debug))]122pub struct FungibleItemType<AccountId> {123    pub collection: u64,124    pub owner: AccountId,125    pub value: u128,126}127128#[derive(Encode, Decode, Default, Clone, PartialEq)]129#[cfg_attr(feature = "std", derive(Debug))]130pub struct ReFungibleItemType<AccountId> {131    pub collection: u64,132    pub owner: Vec<Ownership<AccountId>>,133    pub data: Vec<u8>,134}135136#[derive(Encode, Decode, Default, Clone, PartialEq)]137#[cfg_attr(feature = "std", derive(Debug))]138pub struct ApprovePermissions<AccountId> {139    pub approved: AccountId,140    pub amount: u64,141}142143#[derive(Encode, Decode, Default, Clone, PartialEq)]144#[cfg_attr(feature = "std", derive(Debug))]145pub struct VestingItem<AccountId, Moment> {146    pub sender: AccountId,147    pub recipient: AccountId,148    pub collection_id: u64,149    pub item_id: u64,150    pub amount: u64,151    pub vesting_date: Moment,152}153154pub trait Trait: system::Trait {155    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;156}157158decl_storage! {159    trait Store for Module<T: Trait> as Nft {160161        // Private members162        NextCollectionID: u64;163        ItemListIndex: map hasher(blake2_128_concat) u64 => u64;164165        pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;166        pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;167        pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;168169        /// Balance owner per collection map170        pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;171172        /// second parameter: item id + owner account id173        pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) (u64, T::AccountId) => Vec<ApprovePermissions<T::AccountId>>;174175        /// Item collections176        pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;177        pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;178        pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;179180        // Active vesting list181        // pub VestingList get(fn vesting): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => VestingItem<T::AccountId, T::Moment>;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        // Create collection of NFT with given parameters209        //210        // @param customDataSz size of custom data in each collection item211        // returns collection ID212        #[weight = 0]213        pub fn create_collection(   origin,214                                    collection_name: Vec<u16>,215                                    collection_description: Vec<u16>,216                                    token_prefix: Vec<u8>,217                                    mode: CollectionMode) -> DispatchResult {218219            // Anyone can create a collection220            let who = ensure_signed(origin)?;221            let custom_data_size = match mode {222                CollectionMode::NFT(size) => size,223                CollectionMode::ReFungible(size, _) => size,224                _ => 0225            };226227            let decimal_points = match mode {228                CollectionMode::Fungible(points) => points,229                CollectionMode::ReFungible(_, points) => points,230                _ => 0231            };232233            // check params234            ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4");235236            let mut name = collection_name.to_vec();237            name.push(0);238            ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");239240            let mut description = collection_description.to_vec();241            description.push(0);242            ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");243244            let mut prefix = token_prefix.to_vec();245            prefix.push(0);246            ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");247248            // Generate next collection ID249            let next_id = NextCollectionID::get()250                .checked_add(1)251                .expect("collection id error");252253            NextCollectionID::put(next_id);254255            // Create new collection256            let new_collection = CollectionType {257                owner: who.clone(),258                name: name,259                mode: mode.clone(),260                access: AccessMode::Normal,261                description: description,262                decimal_points: decimal_points,263                token_prefix: prefix,264                offchain_schema: Vec::new(),265                custom_data_size: custom_data_size,266                sponsor: T::AccountId::default(),267                unconfirmed_sponsor: T::AccountId::default(),268            };269270            // Add new collection to map271            <Collection<T>>::insert(next_id, new_collection);272273            // call event274            Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));275276            Ok(())277        }278279        #[weight = 0]280        pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {281282            let sender = ensure_signed(origin)?;283            Self::check_owner_permissions(collection_id, sender)?;284285            // TODO Items remove286            <AddressTokens<T>>::remove_prefix(collection_id);287            <ApprovedList<T>>::remove_prefix(collection_id);288            <Balance<T>>::remove_prefix(collection_id);289            <ItemListIndex>::remove(collection_id);290            <AdminList<T>>::remove(collection_id);291            <Collection<T>>::remove(collection_id);292            <WhiteList<T>>::remove(collection_id);293294            Ok(())295        }296297        #[weight = 0]298        pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {299300            let sender = ensure_signed(origin)?;301            Self::check_owner_permissions(collection_id, sender)?;302            let mut target_collection = <Collection<T>>::get(collection_id);303            target_collection.owner = new_owner;304            <Collection<T>>::insert(collection_id, target_collection);305306            Ok(())307        }308309        #[weight = 0]310        pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {311312            let sender = ensure_signed(origin)?;313            Self::check_owner_or_admin_permissions(collection_id, sender)?;314            let mut admin_arr: Vec<T::AccountId> = Vec::new();315316            if <AdminList<T>>::contains_key(collection_id)317            {318                admin_arr = <AdminList<T>>::get(collection_id);319                ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");320            }321322            admin_arr.push(new_admin_id);323            <AdminList<T>>::insert(collection_id, admin_arr);324325            Ok(())326        }327328        #[weight = 0]329        pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {330331            let sender = ensure_signed(origin)?;332            Self::check_owner_or_admin_permissions(collection_id, sender)?;333334            if <AdminList<T>>::contains_key(collection_id)335            {336                let mut admin_arr = <AdminList<T>>::get(collection_id);337                admin_arr.retain(|i| *i != account_id);338                <AdminList<T>>::insert(collection_id, admin_arr);339            }340341            Ok(())342        }343344        #[weight = 0]345        pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {346347            let sender = ensure_signed(origin)?;348            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");349350            let mut target_collection = <Collection<T>>::get(collection_id);351            ensure!(sender == target_collection.owner, "You do not own this collection");352353            target_collection.unconfirmed_sponsor = new_sponsor;354            <Collection<T>>::insert(collection_id, target_collection);355356            Ok(())357        }358359        #[weight = 0]360        pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {361362            let sender = ensure_signed(origin)?;363            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");364365            let mut target_collection = <Collection<T>>::get(collection_id);366            ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");367368            target_collection.sponsor = target_collection.unconfirmed_sponsor;369            target_collection.unconfirmed_sponsor = T::AccountId::default();370            <Collection<T>>::insert(collection_id, target_collection);371372            Ok(())373        }374375        #[weight = 0]376        pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {377378            let sender = ensure_signed(origin)?;379            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");380381            let mut target_collection = <Collection<T>>::get(collection_id);382            ensure!(sender == target_collection.owner, "You do not own this collection");383384            target_collection.sponsor = T::AccountId::default();385            <Collection<T>>::insert(collection_id, target_collection);386387            Ok(())388        }389390        #[weight = 0]391        pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {392393            let sender = ensure_signed(origin)?;394            let target_collection = <Collection<T>>::get(collection_id);395            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;396397            match target_collection.mode398            {399                CollectionMode::NFT(_) => {400401                    // check size402                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");403404                    // Create nft item405                    let item = NftItemType {406                        collection: collection_id,407                        owner: owner,408                        data: properties,409                    };410411                    Self::add_nft_item(item)?;412413                },414                CollectionMode::Fungible(_) => {415416                    // check size417                    ensure!(properties.len() as u32 == 0, "Size of item must be 0 with fungible type");418419                    let item = FungibleItemType {420                        collection: collection_id,421                        owner: owner,422                        value: (10 as u128).pow(target_collection.decimal_points)423                    };424425                    Self::add_fungible_item(item)?;426                },427                CollectionMode::ReFungible(_, _) => {428429                    // check size430                    ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");431432                    let mut owner_list = Vec::new();433                    let value = (10 as u128).pow(target_collection.decimal_points);434                    owner_list.push(Ownership {owner: owner, fraction: value});435436                    let item = ReFungibleItemType {437                        collection: collection_id,438                        owner: owner_list,439                        data: properties440                    };441442                    Self::add_refungible_item(item)?;443                },444                _ => ()445            };446447            // call event448            Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));449450            Ok(())451        }452453        #[weight = 0]454        pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {455456            let sender = ensure_signed(origin)?;457            let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);458            if !item_owner459            {460                Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;461            }462            let target_collection = <Collection<T>>::get(collection_id);463464            match target_collection.mode465            {466                CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,467                CollectionMode::Fungible(_)  => Self::burn_fungible_item(collection_id, item_id)?,468                CollectionMode::ReFungible(_, _)  => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,469                _ => ()470            };471472            // call event473            Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));474475            Ok(())476        }477478        #[weight = 0]479        pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {480481            let sender = ensure_signed(origin)?;482            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");483484            let target_collection = <Collection<T>>::get(collection_id);485486            // TODO: implement other modes487            match target_collection.mode488            {489                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,490                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,491                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,492                _ => ()493            };494495            Ok(())496        }497498        #[weight = 0]499        pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {500501            let sender = ensure_signed(origin)?;502503            // amount param stub504            let amount = 100000000;505506            ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");507508            let list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, sender.clone()));509            if list_exists {510511                let mut list = <ApprovedList<T>>::get(collection_id, (item_id, sender.clone()));512                let item_contains = list.iter().any(|i| i.approved == approved);513514                if !item_contains {515                    list.push(ApprovePermissions { approved: approved.clone(), amount: amount });516                    <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);517                }518            } else {519520                let mut list = Vec::new();521                list.push(ApprovePermissions { approved: approved.clone(), amount: amount });522                <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);523            }524525            Ok(())526        }527528        #[weight = 0]529        pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {530531            let sender = ensure_signed(origin)?;532            let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, from.clone()));533            if approved_list_exists534            {535                let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));536                let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());537                ensure!(opt_item.is_some(), "No approve found");538                ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved");539540                // remove approve541                let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))542                    .into_iter().filter(|i| i.approved != sender.clone()).collect();543                <ApprovedList<T>>::insert(collection_id, (item_id, from.clone()), approve_list);544            }545            else546            {547                Self::check_owner_or_admin_permissions(collection_id, sender)?;548            }549550            let target_collection = <Collection<T>>::get(collection_id);551552            match target_collection.mode553            {554                CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,555                CollectionMode::Fungible(_)  => Self::transfer_fungible(collection_id, item_id, value, from.clone(), recipient)?,556                CollectionMode::ReFungible(_, _)  => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,557                _ => ()558            };559560            Ok(())561        }562563        #[weight = 0]564        pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {565566            // let no_perm_mes = "You do not have permissions to modify this collection";567            // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);568            // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));569            // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);570571            // // on_nft_received  call572573            // Self::transfer(origin, collection_id, item_id, new_owner)?;574575            Ok(())576        }577578        #[weight = 0]579        pub fn set_offchain_schema(580            origin,581            collection_id: u64,582            schema: Vec<u8>583        ) -> DispatchResult {584            let sender = ensure_signed(origin)?;585            Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;586587            let mut target_collection = <Collection<T>>::get(collection_id);588            target_collection.offchain_schema = schema;589            <Collection<T>>::insert(collection_id, target_collection);590591            Ok(())592        }593    }594}595596impl<T: Trait> Module<T> {597    fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {598        let current_index = <ItemListIndex>::get(item.collection)599            .checked_add(1)600            .expect("Item list index id error");601        let itemcopy = item.clone();602        let owner = item.owner.clone();603        let value = item.value as u64;604605        Self::add_token_index(item.collection, current_index, owner.clone())?;606607        <ItemListIndex>::insert(item.collection, current_index);608        <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);609610        // Update balance611        let new_balance = <Balance<T>>::get(item.collection, owner.clone())612            .checked_add(value)613            .unwrap();614        <Balance<T>>::insert(item.collection, owner.clone(), new_balance);615616        Ok(())617    }618619    fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {620        let current_index = <ItemListIndex>::get(item.collection)621            .checked_add(1)622            .expect("Item list index id error");623        let itemcopy = item.clone();624625        let value = item.owner.first().unwrap().fraction as u64;626        let owner = item.owner.first().unwrap().owner.clone();627628        Self::add_token_index(item.collection, current_index, owner.clone())?;629630        <ItemListIndex>::insert(item.collection, current_index);631        <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);632633        // Update balance634        let new_balance = <Balance<T>>::get(item.collection, owner.clone())635            .checked_add(value)636            .unwrap();637        <Balance<T>>::insert(item.collection, owner.clone(), new_balance);638639        Ok(())640    }641642    fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {643        let current_index = <ItemListIndex>::get(item.collection)644            .checked_add(1)645            .expect("Item list index id error");646647        let item_owner = item.owner.clone();648        let collection_id = item.collection.clone();649        Self::add_token_index(collection_id, current_index, item.owner.clone())?;650651        <ItemListIndex>::insert(collection_id, current_index);652        <NftItemList<T>>::insert(collection_id, current_index, item);653654        // Update balance655        let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())656            .checked_add(1)657            .unwrap();658        <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);659660        Ok(())661    }662663    fn burn_refungible_item(664        collection_id: u64,665        item_id: u64,666        owner: T::AccountId,667    ) -> DispatchResult {668        ensure!(669            <ReFungibleItemList<T>>::contains_key(collection_id, item_id),670            "Item does not exists"671        );672        let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);673        let item = collection674            .owner675            .iter()676            .filter(|&i| i.owner == owner)677            .next()678            .unwrap();679        Self::remove_token_index(collection_id, item_id, owner.clone())?;680681        // remove approve list682        <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));683684        // update balance685        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())686            .checked_sub(item.fraction as u64)687            .unwrap();688        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);689690        <ReFungibleItemList<T>>::remove(collection_id, item_id);691692        Ok(())693    }694695    fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {696        ensure!(697            <NftItemList<T>>::contains_key(collection_id, item_id),698            "Item does not exists"699        );700        let item = <NftItemList<T>>::get(collection_id, item_id);701        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;702703        // remove approve list704        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));705706        // update balance707        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())708            .checked_sub(1)709            .unwrap();710        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);711        <NftItemList<T>>::remove(collection_id, item_id);712713        Ok(())714    }715716    fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {717        ensure!(718            <FungibleItemList<T>>::contains_key(collection_id, item_id),719            "Item does not exists"720        );721        let item = <FungibleItemList<T>>::get(collection_id, item_id);722        Self::remove_token_index(collection_id, item_id, item.owner.clone())?;723724        // remove approve list725        <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));726727        // update balance728        let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())729            .checked_sub(item.value as u64)730            .unwrap();731        <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);732733        <FungibleItemList<T>>::remove(collection_id, item_id);734735        Ok(())736    }737738    fn collection_exists(collection_id: u64) -> DispatchResult {739        ensure!(740            <Collection<T>>::contains_key(collection_id),741            "This collection does not exist"742        );743        Ok(())744    }745746    fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {747        Self::collection_exists(collection_id)?;748749        let target_collection = <Collection<T>>::get(collection_id);750        ensure!(751            subject == target_collection.owner,752            "You do not own this collection"753        );754755        Ok(())756    }757758    fn check_owner_or_admin_permissions(759        collection_id: u64,760        subject: T::AccountId,761    ) -> DispatchResult {762        Self::collection_exists(collection_id)?;763764        let target_collection = <Collection<T>>::get(collection_id);765        let is_owner = subject == target_collection.owner;766767        let no_perm_mes = "You do not have permissions to modify this collection";768        let exists = <AdminList<T>>::contains_key(collection_id);769770        if !is_owner {771            ensure!(exists, no_perm_mes);772            ensure!(773                <AdminList<T>>::get(collection_id).contains(&subject),774                no_perm_mes775            );776        }777        Ok(())778    }779780    fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool {781        let target_collection = <Collection<T>>::get(collection_id);782783        match target_collection.mode {784            CollectionMode::NFT(_) => {785                <NftItemList<T>>::get(collection_id, item_id).owner == subject786            }787            CollectionMode::Fungible(_) => {788                <FungibleItemList<T>>::get(collection_id, item_id).owner == subject789            }790            CollectionMode::ReFungible(_, _) => {791                <ReFungibleItemList<T>>::get(collection_id, item_id)792                    .owner793                    .iter()794                    .any(|i| i.owner == subject)795            }796            CollectionMode::Invalid => false,797        }798    }799800    fn transfer_fungible(801        collection_id: u64,802        item_id: u64,803        value: u64,804        owner: T::AccountId,805        new_owner: T::AccountId,806    ) -> DispatchResult {807        let full_item = <FungibleItemList<T>>::get(collection_id, item_id);808        let amount = full_item.value;809810        ensure!(amount >= value.into(), "Item balance not enouth");811812        // update balance813        let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone())814            .checked_sub(value)815            .unwrap();816        <Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);817818        let mut new_owner_account_id = 0;819        let new_owner_items = <AddressTokens<T>>::get(collection_id, new_owner.clone());820        if new_owner_items.len() > 0 {821            new_owner_account_id = new_owner_items[0];822        }823824        let val64 = value.into();825826        // transfer827        if amount == val64 && new_owner_account_id == 0 {828            // change owner829            // new owner do not have account830            let mut new_full_item = full_item.clone();831            new_full_item.owner = new_owner.clone();832            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);833834            // update balance835            let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())836                .checked_add(value)837                .unwrap();838            <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);839840            // update index collection841            Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;842        } else {843            let mut new_full_item = full_item.clone();844            new_full_item.value -= val64;845846            // separate amount847            if new_owner_account_id > 0 {848                // new owner has account849                let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);850                item.value += val64;851852                // update balance853                let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())854                    .checked_add(value)855                    .unwrap();856                <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);857858                <FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);859            } else {860                // new owner do not have account861                let item = FungibleItemType {862                    collection: collection_id,863                    owner: new_owner.clone(),864                    value: val64,865                };866867                Self::add_fungible_item(item)?;868            }869870            if amount == val64 {871                Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;872873                // remove approve list874                <ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));875                <FungibleItemList<T>>::remove(collection_id, item_id);876            }877878            <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);879        }880881        Ok(())882    }883884    fn transfer_refungible(885        collection_id: u64,886        item_id: u64,887        value: u64,888        owner: T::AccountId,889        new_owner: T::AccountId,890    ) -> DispatchResult {891        let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);892        let item = full_item893            .owner894            .iter()895            .filter(|i| i.owner == owner)896            .next()897            .unwrap();898        let amount = item.fraction;899900        ensure!(amount >= value.into(), "Item balance not enouth");901902        // update balance903        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())904            .checked_sub(value)905            .unwrap();906        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);907908        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())909            .checked_add(value)910            .unwrap();911        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);912913        let old_owner = item.owner.clone();914        let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);915        let val64 = value.into();916917        // transfer918        if amount == val64 && !new_owner_has_account {919            // change owner920            // new owner do not have account921            let mut new_full_item = full_item.clone();922            new_full_item923                .owner924                .iter_mut()925                .find(|i| i.owner == owner)926                .unwrap()927                .owner = new_owner.clone();928            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);929930            // update index collection931            Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;932        } else {933            let mut new_full_item = full_item.clone();934            new_full_item935                .owner936                .iter_mut()937                .find(|i| i.owner == owner)938                .unwrap()939                .fraction -= val64;940941            // separate amount942            if new_owner_has_account {943                // new owner has account944                new_full_item945                    .owner946                    .iter_mut()947                    .find(|i| i.owner == new_owner)948                    .unwrap()949                    .fraction += val64;950            } else {951                // new owner do not have account952                new_full_item.owner.push(Ownership {953                    owner: new_owner.clone(),954                    fraction: val64,955                });956                Self::add_token_index(collection_id, item_id, new_owner.clone())?;957            }958959            <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);960        }961962        Ok(())963    }964965    fn transfer_nft(966        collection_id: u64,967        item_id: u64,968        sender: T::AccountId,969        new_owner: T::AccountId,970    ) -> DispatchResult {971        let mut item = <NftItemList<T>>::get(collection_id, item_id);972973        ensure!(974            sender == item.owner,975            "sender parameter and item owner must be equal"976        );977978        // update balance979        let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())980            .checked_sub(1)981            .unwrap();982        <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);983984        let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())985            .checked_add(1)986            .unwrap();987        <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);988989        // change owner990        let old_owner = item.owner.clone();991        item.owner = new_owner.clone();992        <NftItemList<T>>::insert(collection_id, item_id, item);993994        // update index collection995        Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;996997        // reset approved list998        <ApprovedList<T>>::remove(collection_id, (item_id, old_owner));999        Ok(())1000    }10011002    fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {1003        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1004        if list_exists {1005            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1006            let item_contains = list.contains(&item_index.clone());10071008            if !item_contains {1009                list.push(item_index.clone());1010            }10111012            <AddressTokens<T>>::insert(collection_id, owner.clone(), list);1013        } else {1014            let mut itm = Vec::new();1015            itm.push(item_index.clone());1016            <AddressTokens<T>>::insert(collection_id, owner, itm);1017        }10181019        Ok(())1020    }10211022    fn remove_token_index(1023        collection_id: u64,1024        item_index: u64,1025        owner: T::AccountId,1026    ) -> DispatchResult {1027        let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1028        if list_exists {1029            let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1030            let item_contains = list.contains(&item_index.clone());10311032            if item_contains {1033                list.retain(|&item| item != item_index);1034                <AddressTokens<T>>::insert(collection_id, owner, list);1035            }1036        }10371038        Ok(())1039    }10401041    fn move_token_index(1042        collection_id: u64,1043        item_index: u64,1044        old_owner: T::AccountId,1045        new_owner: T::AccountId,1046    ) -> DispatchResult {1047        Self::remove_token_index(collection_id, item_index, old_owner)?;1048        Self::add_token_index(collection_id, item_index, new_owner)?;10491050        Ok(())1051    }1052}10531054////////////////////////////////////////////////////////////////////////////////////////////////////1055// Economic models10561057/// Fee multiplier.1058pub type Multiplier = FixedU128;10591060type BalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1061    <T as system::Trait>::AccountId,1062>>::Balance;1063type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1064    <T as system::Trait>::AccountId,1065>>::NegativeImbalance;10661067/// Require the transactor pay for themselves and maybe include a tip to gain additional priority1068/// in the queue.1069#[derive(Encode, Decode, Clone, Eq, PartialEq)]1070pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(1071    #[codec(compact)] BalanceOf<T>,1072);10731074impl<T: Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug1075    for ChargeTransactionPayment<T>1076{1077    #[cfg(feature = "std")]1078    fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1079        write!(f, "ChargeTransactionPayment<{:?}>", self.0)1080    }1081    #[cfg(not(feature = "std"))]1082    fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1083        Ok(())1084    }1085}10861087impl<T: Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T>1088where1089    T::Call:1090        Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1091    BalanceOf<T>: Send + Sync + FixedPointOperand,1092{1093    /// utility constructor. Used only in client/factory code.1094    pub fn from(fee: BalanceOf<T>) -> Self {1095        Self(fee)1096    }10971098    pub fn traditional_fee(1099        len: usize,1100        info: &DispatchInfoOf<T::Call>,1101        tip: BalanceOf<T>,1102    ) -> BalanceOf<T>1103    where1104        T::Call: Dispatchable<Info = DispatchInfo>,1105    {1106        <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)1107    }11081109    fn withdraw_fee(1110        &self,1111        who: &T::AccountId,1112        call: &T::Call,1113        info: &DispatchInfoOf<T::Call>,1114        len: usize,1115    ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {1116        let tip = self.0;11171118        // Set fee based on call type. Creating collection costs 1 Unique.1119        // All other transactions have traditional fees so far1120        let fee = match call.is_sub_type() {1121            Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1122            _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes1123                                                        // _ => <BalanceOf<T>>::from(100)1124        };11251126        // Determine who is paying transaction fee based on ecnomic model1127        // Parse call to extract collection ID and access collection sponsor1128        let sponsor: T::AccountId = match call.is_sub_type() {1129            Some(Call::create_item(collection_id, _properties, _owner)) => {1130                <Collection<T>>::get(collection_id).sponsor1131            }1132            Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {1133                <Collection<T>>::get(collection_id).sponsor1134            }11351136            _ => T::AccountId::default(),1137        };11381139        let mut who_pays_fee: T::AccountId = sponsor.clone();1140        if sponsor == T::AccountId::default() {1141            who_pays_fee = who.clone();1142        }11431144        // Only mess with balances if fee is not zero.1145        if fee.is_zero() {1146            return Ok((fee, None));1147        }11481149        match <T as transaction_payment::Trait>::Currency::withdraw(1150            &who_pays_fee,1151            fee,1152            if tip.is_zero() {1153                WithdrawReason::TransactionPayment.into()1154            } else {1155                WithdrawReason::TransactionPayment | WithdrawReason::Tip1156            },1157            ExistenceRequirement::KeepAlive,1158        ) {1159            Ok(imbalance) => Ok((fee, Some(imbalance))),1160            Err(_) => Err(InvalidTransaction::Payment.into()),1161        }1162    }1163}11641165impl<T: Trait + transaction_payment::Trait + Send + Sync> SignedExtension1166    for ChargeTransactionPayment<T>1167where1168    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,1169    T::Call:1170        Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1171{1172    const IDENTIFIER: &'static str = "ChargeTransactionPayment";1173    type AccountId = T::AccountId;1174    type Call = T::Call;1175    type AdditionalSigned = ();1176    type Pre = (1177        BalanceOf<T>,1178        Self::AccountId,1179        Option<NegativeImbalanceOf<T>>,1180        BalanceOf<T>,1181    );1182    fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {1183        Ok(())1184    }11851186    fn validate(1187        &self,1188        who: &Self::AccountId,1189        call: &Self::Call,1190        info: &DispatchInfoOf<Self::Call>,1191        len: usize,1192    ) -> TransactionValidity {1193        let (fee, _) = self.withdraw_fee(who, call, info, len)?;11941195        let mut r = ValidTransaction::default();1196        // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which1197        // will be a bit more than setting the priority to tip. For now, this is enough.1198        r.priority = fee.saturated_into::<TransactionPriority>();1199        Ok(r)1200    }12011202    fn pre_dispatch(1203        self,1204        who: &Self::AccountId,1205        call: &Self::Call,1206        info: &DispatchInfoOf<Self::Call>,1207        len: usize,1208    ) -> Result<Self::Pre, TransactionValidityError> {1209        let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;1210        Ok((self.0, who.clone(), imbalance, fee))1211    }12121213    fn post_dispatch(1214        pre: Self::Pre,1215        info: &DispatchInfoOf<Self::Call>,1216        post_info: &PostDispatchInfoOf<Self::Call>,1217        len: usize,1218        _result: &DispatchResult,1219    ) -> Result<(), TransactionValidityError> {1220        let (tip, who, imbalance, fee) = pre;1221        if let Some(payed) = imbalance {1222            let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(1223                len as u32, info, post_info, tip,1224            );1225            let refund = fee.saturating_sub(actual_fee);1226            let actual_payment =1227                match <T as transaction_payment::Trait>::Currency::deposit_into_existing(1228                    &who, refund,1229                ) {1230                    Ok(refund_imbalance) => {1231                        // The refund cannot be larger than the up front payed max weight.1232                        // `PostDispatchInfo::calc_unspent` guards against such a case.1233                        match payed.offset(refund_imbalance) {1234                            Ok(actual_payment) => actual_payment,1235                            Err(_) => return Err(InvalidTransaction::Payment.into()),1236                        }1237                    }1238                    // We do not recreate the account using the refund. The up front payment1239                    // is gone in that case.1240                    Err(_) => payed,1241                };1242            let imbalances = actual_payment.split(tip);1243            <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(1244                Some(imbalances.0).into_iter().chain(Some(imbalances.1)),1245            );1246        }1247        Ok(())1248    }1249}
modifiedpallets/nft/src/mock.rsdiffbeforeafterboth
--- a/pallets/nft/src/mock.rs
+++ b/pallets/nft/src/mock.rs
@@ -1,19 +1,19 @@
 // Creating mock runtime here
 
 use crate::{Module, Trait};
+use frame_support::{
+    impl_outer_origin, parameter_types,
+    weights::{
+        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight},
+        Weight,
+    },
+};
 use frame_system as system;
 use sp_core::H256;
 use sp_runtime::{
     testing::Header,
     traits::{BlakeTwo256, IdentityLookup, Saturating},
     Perbill,
-};
-use frame_support::{
-    parameter_types, impl_outer_origin,
-    weights::{
-        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight},
-        Weight,
-    },
 };
 
 impl_outer_origin! {
@@ -49,9 +49,9 @@
     type MaximumBlockWeight = MaximumBlockWeight;
     type MaximumBlockLength = MaximumBlockLength;
     type AvailableBlockRatio = AvailableBlockRatio;
-    type BaseCallFilter = (); 
-    type DbWeight = RocksDbWeight; 
-    type BlockExecutionWeight = BlockExecutionWeight; 
+    type BaseCallFilter = ();
+    type DbWeight = RocksDbWeight;
+    type BlockExecutionWeight = BlockExecutionWeight;
     type ExtrinsicBaseWeight = ExtrinsicBaseWeight;
     type MaximumExtrinsicWeight = MaximumExtrinsicWeight;
     type Version = ();
modifiedpallets/nft/src/tests.rsdiffbeforeafterboth
--- a/pallets/nft/src/tests.rs
+++ b/pallets/nft/src/tests.rs
@@ -1,6 +1,6 @@
 // Tests to be written here
 use crate::mock::*;
-use crate::{CollectionMode, Ownership, ApprovePermissions};
+use crate::{ApprovePermissions, CollectionMode, Ownership};
 use frame_support::{assert_noop, assert_ok};
 
 #[test]
@@ -21,9 +21,13 @@
         ));
         assert_eq!(TemplateModule::collection(1).owner, 1);
 
-
-        assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));
-        assert_eq!(TemplateModule::nft_item_id(1,1).data, [1,2,3].to_vec());
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+        assert_eq!(TemplateModule::nft_item_id(1, 1).data, [1, 2, 3].to_vec());
     });
 }
 
@@ -45,10 +49,23 @@
         ));
         assert_eq!(TemplateModule::collection(1).owner, 1);
 
-
-        assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));
-        assert_eq!(TemplateModule::refungible_item_id(1,1).data, [1,2,3].to_vec());
-        assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 1, fraction: 1000 });
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).data,
+            [1, 2, 3].to_vec()
+        );
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).owner[0],
+            Ownership {
+                owner: 1,
+                fraction: 1000
+            }
+        );
     });
 }
 
@@ -70,10 +87,15 @@
         ));
         assert_eq!(TemplateModule::collection(1).owner, 1);
 
-        assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [].to_vec(), 1));
-        assert_eq!(TemplateModule::fungible_item_id(1,1).owner, 1);
-        assert_eq!(TemplateModule::balance_count(1,1), 1000);
-        assert_eq!(TemplateModule::address_tokens(1,1), [1]);
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [].to_vec(),
+            1
+        ));
+        assert_eq!(TemplateModule::fungible_item_id(1, 1).owner, 1);
+        assert_eq!(TemplateModule::balance_count(1, 1), 1000);
+        assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
     });
 }
 
@@ -96,37 +118,42 @@
         ));
         assert_eq!(TemplateModule::collection(1).owner, 1);
 
-        assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [].to_vec(), 1));
-        assert_eq!(TemplateModule::fungible_item_id(1,1).owner, 1);
-        assert_eq!(TemplateModule::balance_count(1,1), 1000);
-        assert_eq!(TemplateModule::address_tokens(1,1), [1]);
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [].to_vec(),
+            1
+        ));
+        assert_eq!(TemplateModule::fungible_item_id(1, 1).owner, 1);
+        assert_eq!(TemplateModule::balance_count(1, 1), 1000);
+        assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
 
         // change owner scenario
         assert_ok!(TemplateModule::transfer(origin1.clone(), 2, 1, 1, 1000));
-        assert_eq!(TemplateModule::fungible_item_id(1,1).owner, 2);
-        assert_eq!(TemplateModule::fungible_item_id(1,1).value, 1000);
-        assert_eq!(TemplateModule::balance_count(1,1), 0);
-        assert_eq!(TemplateModule::balance_count(1,2), 1000);
-        assert_eq!(TemplateModule::address_tokens(1,1), []);
-        assert_eq!(TemplateModule::address_tokens(1,2), [1]);
+        assert_eq!(TemplateModule::fungible_item_id(1, 1).owner, 2);
+        assert_eq!(TemplateModule::fungible_item_id(1, 1).value, 1000);
+        assert_eq!(TemplateModule::balance_count(1, 1), 0);
+        assert_eq!(TemplateModule::balance_count(1, 2), 1000);
+        assert_eq!(TemplateModule::address_tokens(1, 1), []);
+        assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
 
         // split item scenario
         assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 500));
-        assert_eq!(TemplateModule::fungible_item_id(1,1).owner, 2);
-        assert_eq!(TemplateModule::fungible_item_id(1,2).owner, 3);
-        assert_eq!(TemplateModule::balance_count(1,2), 500);
-        assert_eq!(TemplateModule::balance_count(1,3), 500);
-        assert_eq!(TemplateModule::address_tokens(1,2), [1]);
-        assert_eq!(TemplateModule::address_tokens(1,3), [2]);
+        assert_eq!(TemplateModule::fungible_item_id(1, 1).owner, 2);
+        assert_eq!(TemplateModule::fungible_item_id(1, 2).owner, 3);
+        assert_eq!(TemplateModule::balance_count(1, 2), 500);
+        assert_eq!(TemplateModule::balance_count(1, 3), 500);
+        assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
+        assert_eq!(TemplateModule::address_tokens(1, 3), [2]);
 
         // split item and new owner has account scenario
         assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 200));
-        assert_eq!(TemplateModule::fungible_item_id(1,1).value, 300);
-        assert_eq!(TemplateModule::fungible_item_id(1,2).value, 700);
-        assert_eq!(TemplateModule::balance_count(1,2), 300);
-        assert_eq!(TemplateModule::balance_count(1,3), 700);
-        assert_eq!(TemplateModule::address_tokens(1,2), [1]);
-        assert_eq!(TemplateModule::address_tokens(1,3), [2]);
+        assert_eq!(TemplateModule::fungible_item_id(1, 1).value, 300);
+        assert_eq!(TemplateModule::fungible_item_id(1, 2).value, 700);
+        assert_eq!(TemplateModule::balance_count(1, 2), 300);
+        assert_eq!(TemplateModule::balance_count(1, 3), 700);
+        assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
+        assert_eq!(TemplateModule::address_tokens(1, 3), [2]);
     });
 }
 
@@ -149,37 +176,81 @@
         ));
         assert_eq!(TemplateModule::collection(1).owner, 1);
 
-        assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));
-        assert_eq!(TemplateModule::refungible_item_id(1,1).data, [1,2,3].to_vec());
-        assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 1, fraction: 1000 });
-        assert_eq!(TemplateModule::balance_count(1,1), 1000);
-        assert_eq!(TemplateModule::address_tokens(1,1), [1]);
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).data,
+            [1, 2, 3].to_vec()
+        );
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).owner[0],
+            Ownership {
+                owner: 1,
+                fraction: 1000
+            }
+        );
+        assert_eq!(TemplateModule::balance_count(1, 1), 1000);
+        assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
 
         // change owner scenario
         assert_ok!(TemplateModule::transfer(origin1.clone(), 2, 1, 1, 1000));
-        assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 2, fraction: 1000 });
-        assert_eq!(TemplateModule::balance_count(1,1), 0);
-        assert_eq!(TemplateModule::balance_count(1,2), 1000);
-        assert_eq!(TemplateModule::address_tokens(1,1), []);
-        assert_eq!(TemplateModule::address_tokens(1,2), [1]);
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).owner[0],
+            Ownership {
+                owner: 2,
+                fraction: 1000
+            }
+        );
+        assert_eq!(TemplateModule::balance_count(1, 1), 0);
+        assert_eq!(TemplateModule::balance_count(1, 2), 1000);
+        assert_eq!(TemplateModule::address_tokens(1, 1), []);
+        assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
 
         // split item scenario
         assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 500));
-        assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 2, fraction: 500 });
-        assert_eq!(TemplateModule::refungible_item_id(1,1).owner[1], Ownership { owner: 3, fraction: 500 });
-        assert_eq!(TemplateModule::balance_count(1,2), 500);
-        assert_eq!(TemplateModule::balance_count(1,3), 500);
-        assert_eq!(TemplateModule::address_tokens(1,2), [1]);
-        assert_eq!(TemplateModule::address_tokens(1,3), [1]);
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).owner[0],
+            Ownership {
+                owner: 2,
+                fraction: 500
+            }
+        );
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).owner[1],
+            Ownership {
+                owner: 3,
+                fraction: 500
+            }
+        );
+        assert_eq!(TemplateModule::balance_count(1, 2), 500);
+        assert_eq!(TemplateModule::balance_count(1, 3), 500);
+        assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
+        assert_eq!(TemplateModule::address_tokens(1, 3), [1]);
 
         // split item and new owner has account scenario
         assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 200));
-        assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 2, fraction: 300 });
-        assert_eq!(TemplateModule::refungible_item_id(1,1).owner[1], Ownership { owner: 3, fraction: 700 });
-        assert_eq!(TemplateModule::balance_count(1,2), 300);
-        assert_eq!(TemplateModule::balance_count(1,3), 700);
-        assert_eq!(TemplateModule::address_tokens(1,2), [1]);
-        assert_eq!(TemplateModule::address_tokens(1,3), [1]);
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).owner[0],
+            Ownership {
+                owner: 2,
+                fraction: 300
+            }
+        );
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).owner[1],
+            Ownership {
+                owner: 3,
+                fraction: 700
+            }
+        );
+        assert_eq!(TemplateModule::balance_count(1, 2), 300);
+        assert_eq!(TemplateModule::balance_count(1, 3), 700);
+        assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
+        assert_eq!(TemplateModule::address_tokens(1, 3), [1]);
     });
 }
 
@@ -201,19 +272,23 @@
         ));
         assert_eq!(TemplateModule::collection(1).owner, 1);
 
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+        assert_eq!(TemplateModule::nft_item_id(1, 1).data, [1, 2, 3].to_vec());
+        assert_eq!(TemplateModule::balance_count(1, 1), 1);
+        assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
 
-        assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));
-        assert_eq!(TemplateModule::nft_item_id(1,1).data, [1,2,3].to_vec());
-        assert_eq!(TemplateModule::balance_count(1,1), 1);
-        assert_eq!(TemplateModule::address_tokens(1,1), [1]);
-
         // default scenario
         assert_ok!(TemplateModule::transfer(origin1.clone(), 2, 1, 1, 1000));
-        assert_eq!(TemplateModule::nft_item_id(1,1).owner, 2);
-        assert_eq!(TemplateModule::balance_count(1,1), 0);
-        assert_eq!(TemplateModule::balance_count(1,2), 1);
-        assert_eq!(TemplateModule::address_tokens(1,1), []);
-        assert_eq!(TemplateModule::address_tokens(1,2), [1]); 
+        assert_eq!(TemplateModule::nft_item_id(1, 1).owner, 2);
+        assert_eq!(TemplateModule::balance_count(1, 1), 0);
+        assert_eq!(TemplateModule::balance_count(1, 2), 1);
+        assert_eq!(TemplateModule::address_tokens(1, 1), []);
+        assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
     });
 }
 
@@ -235,12 +310,16 @@
             mode
         ));
         assert_eq!(TemplateModule::collection(1).owner, 1);
-
 
-        assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));
-        assert_eq!(TemplateModule::nft_item_id(1,1).data, [1,2,3].to_vec());
-        assert_eq!(TemplateModule::balance_count(1,1), 1);
-        assert_eq!(TemplateModule::address_tokens(1,1), [1]);
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+        assert_eq!(TemplateModule::nft_item_id(1, 1).data, [1, 2, 3].to_vec());
+        assert_eq!(TemplateModule::balance_count(1, 1), 1);
+        assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
 
         assert_noop!(
             TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),
@@ -249,13 +328,26 @@
 
         // do approve
         assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
-        assert_eq!(TemplateModule::approved(1,(1,1)).len(), 1);
+        assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
         assert_ok!(TemplateModule::approve(origin1.clone(), 10, 1, 1));
-        assert_eq!(TemplateModule::approved(1,(1,1)).len(), 2);
-        assert_eq!(TemplateModule::approved(1,(1,1))[0], ApprovePermissions { approved: 2, amount: 100000000});
+        assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 2);
+        assert_eq!(
+            TemplateModule::approved(1, (1, 1))[0],
+            ApprovePermissions {
+                approved: 2,
+                amount: 100000000
+            }
+        );
 
-        assert_ok!(TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1));
-        assert_eq!(TemplateModule::approved(1,(1,1)).len(), 0);
+        assert_ok!(TemplateModule::transfer_from(
+            origin2.clone(),
+            1,
+            3,
+            1,
+            1,
+            1
+        ));
+        assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 0);
     });
 }
 
@@ -278,11 +370,25 @@
         ));
         assert_eq!(TemplateModule::collection(1).owner, 1);
 
-        assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));
-        assert_eq!(TemplateModule::refungible_item_id(1,1).data, [1,2,3].to_vec());
-        assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 1, fraction: 1000 });
-        assert_eq!(TemplateModule::balance_count(1,1), 1000);
-        assert_eq!(TemplateModule::address_tokens(1,1), [1]);
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [1, 2, 3].to_vec(),
+            1
+        ));
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).data,
+            [1, 2, 3].to_vec()
+        );
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).owner[0],
+            Ownership {
+                owner: 1,
+                fraction: 1000
+            }
+        );
+        assert_eq!(TemplateModule::balance_count(1, 1), 1000);
+        assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
 
         assert_noop!(
             TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),
@@ -291,19 +397,38 @@
 
         // do approve
         assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
-        assert_eq!(TemplateModule::approved(1,(1,1)).len(), 1);
+        assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
         assert_ok!(TemplateModule::approve(origin1.clone(), 10, 1, 1));
-        assert_eq!(TemplateModule::approved(1,(1,1)).len(), 2);
-        assert_eq!(TemplateModule::approved(1,(1,1))[0], ApprovePermissions { approved: 2, amount: 100000000});
+        assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 2);
+        assert_eq!(
+            TemplateModule::approved(1, (1, 1))[0],
+            ApprovePermissions {
+                approved: 2,
+                amount: 100000000
+            }
+        );
 
-        assert_ok!(TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 100));
-        assert_eq!(TemplateModule::balance_count(1,1), 900);
-        assert_eq!(TemplateModule::balance_count(1,3), 100);
-        assert_eq!(TemplateModule::address_tokens(1,1), [1]);
-        assert_eq!(TemplateModule::address_tokens(1,3), [1]);
+        assert_ok!(TemplateModule::transfer_from(
+            origin2.clone(),
+            1,
+            3,
+            1,
+            1,
+            100
+        ));
+        assert_eq!(TemplateModule::balance_count(1, 1), 900);
+        assert_eq!(TemplateModule::balance_count(1, 3), 100);
+        assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+        assert_eq!(TemplateModule::address_tokens(1, 3), [1]);
 
-        assert_eq!(TemplateModule::approved(1,(1,1)).len(), 1);
-        assert_eq!(TemplateModule::approved(1,(1,1))[0], ApprovePermissions { approved: 10, amount: 100000000});
+        assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
+        assert_eq!(
+            TemplateModule::approved(1, (1, 1))[0],
+            ApprovePermissions {
+                approved: 10,
+                amount: 100000000
+            }
+        );
     });
 }
 
@@ -326,10 +451,15 @@
         ));
         assert_eq!(TemplateModule::collection(1).owner, 1);
 
-        assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [].to_vec(), 1));
-        assert_eq!(TemplateModule::fungible_item_id(1,1).owner, 1);
-        assert_eq!(TemplateModule::balance_count(1,1), 1000);
-        assert_eq!(TemplateModule::address_tokens(1,1), [1]);
+        assert_ok!(TemplateModule::create_item(
+            origin1.clone(),
+            1,
+            [].to_vec(),
+            1
+        ));
+        assert_eq!(TemplateModule::fungible_item_id(1, 1).owner, 1);
+        assert_eq!(TemplateModule::balance_count(1, 1), 1000);
+        assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
 
         assert_noop!(
             TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),
@@ -338,28 +468,54 @@
 
         // do approve
         assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
-        assert_eq!(TemplateModule::approved(1,(1,1)).len(), 1);
+        assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
         assert_ok!(TemplateModule::approve(origin1.clone(), 10, 1, 1));
-        assert_eq!(TemplateModule::approved(1,(1,1)).len(), 2);
-        assert_eq!(TemplateModule::approved(1,(1,1))[0], ApprovePermissions { approved: 2, amount: 100000000});
+        assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 2);
+        assert_eq!(
+            TemplateModule::approved(1, (1, 1))[0],
+            ApprovePermissions {
+                approved: 2,
+                amount: 100000000
+            }
+        );
 
-        assert_ok!(TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 100));
-        assert_eq!(TemplateModule::balance_count(1,1), 900);
-        assert_eq!(TemplateModule::balance_count(1,3), 100);
-        assert_eq!(TemplateModule::address_tokens(1,1), [1]);
-        assert_eq!(TemplateModule::address_tokens(1,3), [2]);
+        assert_ok!(TemplateModule::transfer_from(
+            origin2.clone(),
+            1,
+            3,
+            1,
+            1,
+            100
+        ));
+        assert_eq!(TemplateModule::balance_count(1, 1), 900);
+        assert_eq!(TemplateModule::balance_count(1, 3), 100);
+        assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+        assert_eq!(TemplateModule::address_tokens(1, 3), [2]);
 
-        assert_eq!(TemplateModule::approved(1,(1,1)).len(), 1);
-        assert_eq!(TemplateModule::approved(1,(1,1))[0], ApprovePermissions { approved: 10, amount: 100000000});
+        assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
+        assert_eq!(
+            TemplateModule::approved(1, (1, 1))[0],
+            ApprovePermissions {
+                approved: 10,
+                amount: 100000000
+            }
+        );
 
         assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
-        assert_ok!(TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 900));
-        assert_eq!(TemplateModule::balance_count(1,1), 0);
-        assert_eq!(TemplateModule::balance_count(1,3), 1000);
-        assert_eq!(TemplateModule::address_tokens(1,1), []);
-        assert_eq!(TemplateModule::address_tokens(1,3), [2]);
+        assert_ok!(TemplateModule::transfer_from(
+            origin2.clone(),
+            1,
+            3,
+            1,
+            1,
+            900
+        ));
+        assert_eq!(TemplateModule::balance_count(1, 1), 0);
+        assert_eq!(TemplateModule::balance_count(1, 3), 1000);
+        assert_eq!(TemplateModule::address_tokens(1, 1), []);
+        assert_eq!(TemplateModule::address_tokens(1, 3), [2]);
 
-        assert_eq!(TemplateModule::approved(1,(1,1)).len(), 0);
+        assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 0);
     });
 }
 
@@ -433,7 +589,7 @@
             1
         ));
 
-        assert_eq!(TemplateModule::nft_item_id(1,1).data, [1,2,3].to_vec());
+        assert_eq!(TemplateModule::nft_item_id(1, 1).data, [1, 2, 3].to_vec());
 
         // check balance (collection with id = 1, user id = 1)
         assert_eq!(TemplateModule::balance_count(1, 1), 1);
@@ -509,11 +665,14 @@
         assert_ok!(TemplateModule::create_item(
             origin2.clone(),
             1,
-            [1,2,3].to_vec(),
+            [1, 2, 3].to_vec(),
             1
         ));
 
-        assert_eq!(TemplateModule::refungible_item_id(1,1).data, [1,2,3].to_vec());
+        assert_eq!(
+            TemplateModule::refungible_item_id(1, 1).data,
+            [1, 2, 3].to_vec()
+        );
 
         // check balance (collection with id = 1, user id = 2)
         assert_eq!(TemplateModule::balance_count(1, 1), 1000);
@@ -769,7 +928,14 @@
         // approve
         assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
         assert_eq!(TemplateModule::approved(1, (1, 1))[0].approved, 2);
-        assert_ok!(TemplateModule::transfer_from(origin2.clone(), 1, 2, 1, 1, 1));
+        assert_ok!(TemplateModule::transfer_from(
+            origin2.clone(),
+            1,
+            2,
+            1,
+            1,
+            1
+        ));
 
         // after transfer
         assert_eq!(TemplateModule::balance_count(1, 1), 0);
modifiedruntime/build.rsdiffbeforeafterboth
--- a/runtime/build.rs
+++ b/runtime/build.rs
@@ -1,10 +1,10 @@
 use wasm_builder_runner::WasmBuilder;
 
 fn main() {
-	WasmBuilder::new()
-		.with_current_project()
-		.with_wasm_builder_from_crates("1.0.11")
-		.export_heap_base()
-		.import_memory()
-		.build()
+    WasmBuilder::new()
+        .with_current_project()
+        .with_wasm_builder_from_crates("1.0.11")
+        .export_heap_base()
+        .import_memory()
+        .build()
 }
modifiedruntime/src/lib.rsdiffbeforeafterboth
--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -16,11 +16,12 @@
 use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
 use sp_runtime::{
     create_runtime_str, generic, impl_opaque_keys,
+    traits::{
+        BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, Saturating,
+        Verify,
+    },
     transaction_validity::{TransactionSource, TransactionValidity},
     ApplyExtrinsicResult, MultiSignature,
-	traits::{
-        BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, Saturating, Verify,
-	},
 };
 use sp_std::prelude::*;
 #[cfg(feature = "std")]
@@ -31,22 +32,24 @@
 pub use balances::Call as BalancesCall;
 pub use contracts::Schedule as ContractsSchedule;
 pub use frame_support::{
-    construct_runtime, parameter_types,
-    traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason},
+    construct_runtime,
+    dispatch::DispatchResult,
+    parameter_types,
+    traits::{
+        Currency, ExistenceRequirement, Get, KeyOwnerProofSystem, OnUnbalanced, Randomness,
+        WithdrawReason,
+    },
     weights::{
-        DispatchInfo, PostDispatchInfo, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
-        IdentityFee, Weight, WeightToFeePolynomial, GetDispatchInfo, Pays,
+        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
+        DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,
+        WeightToFeePolynomial,
     },
     StorageValue,
-	dispatch::DispatchResult,
 };
-use system::{self as system};
 #[cfg(any(feature = "std", test))]
 pub use sp_runtime::BuildStorage;
-use sp_runtime::{
-	Perbill,
-};
-
+use sp_runtime::Perbill;
+use system::{self as system};
 
 pub use timestamp::Call as TimestampCall;
 
@@ -492,4 +495,3 @@
         }
     }
 }
-