1#![cfg_attr(not(feature = "std"), no_std)]23456use 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 44 NFT(u32),45 46 Fungible(u32),47 48 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>, 86 pub description: Vec<u16>, 87 pub token_prefix: Vec<u8>, 88 pub custom_data_size: u32,89 pub offchain_schema: Vec<u8>,90 pub sponsor: AccountId, 91 pub unconfirmed_sponsor: AccountId, 92}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 153 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 161 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;162163 164 pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) (u64, T::AccountId) => Vec<ApprovePermissions<T::AccountId>>;165166 167 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 172 173174 175 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;176177 178 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 200 201 202 203 #[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 211 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 225 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 240 let next_id = NextCollectionID::get()241 .checked_add(1)242 .expect("collection id error");243244 NextCollectionID::put(next_id);245246 247 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 262 <Collection<T>>::insert(next_id, new_collection);263264 265 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 277 <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 389 match target_collection.mode 390 {391 CollectionMode::NFT(_) => {392393 394 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");395396 397 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 409 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 422 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 440 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 465 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 479 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 496 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 533 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 559 560 561 562563 564565 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 605 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 627 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 647 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 661 <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));662663 664 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 680 <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));681682 683 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 697 <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));698699 700 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 760 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 772 if amount == val64 && new_owner_account_id == 0773 {774 775 776 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 781 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 785 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 793 if new_owner_account_id > 0 {794795 796 let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);797 item.value += val64;798799 800 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 808 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 821 <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 839 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 850 if amount == val64 && !new_owner_has_account851 {852 853 854 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 859 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 867 if new_owner_has_account {868 869 new_full_item.owner.iter_mut().find(|i| i.owner == new_owner).unwrap().fraction += val64;870 }871 else872 {873 874 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 891 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 898 let old_owner = item.owner.clone();899 item.owner = new_owner.clone();900 <NftItemList<T>>::insert(collection_id, item_id, item);901902 903 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;904905 906 <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}961962963964965966967pub 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;973974975976977978#[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 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 1021 1022 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 1027 1028 };10291030 1031 1032 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 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 1091 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 1126 1127 match payed.offset(refund_imbalance) {1128 Ok(actual_payment) => actual_payment,1129 Err(_) => return Err(InvalidTransaction::Payment.into()),1130 }1131 }1132 1133 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}