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}124125pub trait Trait: system::Trait {126 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;127128}129130decl_storage! {131 trait Store for Module<T: Trait> as Nft {132133 134 NextCollectionID: u64;135 ItemListIndex: map hasher(blake2_128_concat) u64 => u64;136137 pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;138 pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;139 pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;140141 142 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;143 pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => Vec<T::AccountId>;144145 146 pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;147 pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;148 pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;149150 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;151152 153 pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;154 pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;155 }156}157158decl_event!(159 pub enum Event<T>160 where161 AccountId = <T as system::Trait>::AccountId,162 {163 Created(u64, u8, AccountId),164 ItemCreated(u64, u64),165 ItemDestroyed(u64, u64),166 }167);168169decl_module! {170 pub struct Module<T: Trait> for enum Call where origin: T::Origin {171172 fn deposit_event() = default;173174 175 176 177 178 #[weight = 0]179 pub fn create_collection( origin,180 collection_name: Vec<u16>,181 collection_description: Vec<u16>,182 token_prefix: Vec<u8>,183 mode: CollectionMode) -> DispatchResult {184185 186 let who = ensure_signed(origin)?;187 let custom_data_size = match mode {188 CollectionMode::NFT(size) => size,189 CollectionMode::ReFungible(size, _) => size,190 _ => 0191 };192193 let decimal_points = match mode {194 CollectionMode::Fungible(points) => points,195 CollectionMode::ReFungible(_, points) => points,196 _ => 0197 };198199 200 ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4"); 201202 let mut name = collection_name.to_vec();203 name.push(0);204 ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");205206 let mut description = collection_description.to_vec();207 description.push(0);208 ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");209210 let mut prefix = token_prefix.to_vec();211 prefix.push(0);212 ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");213214 215 let next_id = NextCollectionID::get()216 .checked_add(1)217 .expect("collection id error");218219 NextCollectionID::put(next_id);220221 222 let new_collection = CollectionType {223 owner: who.clone(),224 name: name,225 mode: mode.clone(),226 access: AccessMode::Normal,227 description: description,228 decimal_points: decimal_points,229 token_prefix: prefix,230 offchain_schema: Vec::new(),231 custom_data_size: custom_data_size,232 sponsor: T::AccountId::default(),233 unconfirmed_sponsor: T::AccountId::default(),234 };235236 237 <Collection<T>>::insert(next_id, new_collection);238239 240 Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));241242 Ok(())243 }244245 #[weight = 0]246 pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {247248 let sender = ensure_signed(origin)?;249 Self::check_owner_permissions(collection_id, sender)?;250251 <AddressTokens<T>>::remove_prefix(collection_id);252 <ApprovedList<T>>::remove_prefix(collection_id);253 <Balance<T>>::remove_prefix(collection_id);254 <ItemListIndex>::remove(collection_id);255 <AdminList<T>>::remove(collection_id);256 <Collection<T>>::remove(collection_id);257 <WhiteList<T>>::remove(collection_id);258259 Ok(())260 }261262 #[weight = 0]263 pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {264265 let sender = ensure_signed(origin)?;266 Self::check_owner_permissions(collection_id, sender)?;267 let mut target_collection = <Collection<T>>::get(collection_id);268 target_collection.owner = new_owner;269 <Collection<T>>::insert(collection_id, target_collection);270271 Ok(())272 }273274 #[weight = 0]275 pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {276277 let sender = ensure_signed(origin)?;278 Self::check_owner_or_admin_permissions(collection_id, sender)?;279 let mut admin_arr: Vec<T::AccountId> = Vec::new();280281 if <AdminList<T>>::contains_key(collection_id)282 {283 admin_arr = <AdminList<T>>::get(collection_id);284 ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");285 }286287 admin_arr.push(new_admin_id);288 <AdminList<T>>::insert(collection_id, admin_arr);289290 Ok(())291 }292293 #[weight = 0]294 pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {295296 let sender = ensure_signed(origin)?;297 Self::check_owner_or_admin_permissions(collection_id, sender)?;298299 if <AdminList<T>>::contains_key(collection_id)300 {301 let mut admin_arr = <AdminList<T>>::get(collection_id);302 admin_arr.retain(|i| *i != account_id);303 <AdminList<T>>::insert(collection_id, admin_arr);304 }305306 Ok(())307 }308309 #[weight = 0]310 pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {311312 let sender = ensure_signed(origin)?;313 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");314315 let mut target_collection = <Collection<T>>::get(collection_id);316 ensure!(sender == target_collection.owner, "You do not own this collection");317318 target_collection.unconfirmed_sponsor = new_sponsor;319 <Collection<T>>::insert(collection_id, target_collection);320321 Ok(())322 }323324 #[weight = 0]325 pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {326327 let sender = ensure_signed(origin)?;328 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");329330 let mut target_collection = <Collection<T>>::get(collection_id);331 ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");332333 target_collection.sponsor = target_collection.unconfirmed_sponsor;334 target_collection.unconfirmed_sponsor = T::AccountId::default();335 <Collection<T>>::insert(collection_id, target_collection);336337 Ok(())338 }339340 #[weight = 0]341 pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {342343 let sender = ensure_signed(origin)?;344 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");345346 let mut target_collection = <Collection<T>>::get(collection_id);347 ensure!(sender == target_collection.owner, "You do not own this collection");348349 target_collection.sponsor = T::AccountId::default();350 <Collection<T>>::insert(collection_id, target_collection);351352 Ok(())353 }354 355 #[weight = 0]356 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {357358 let sender = ensure_signed(origin)?;359360 361 let target_collection = <Collection<T>>::get(collection_id);362 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");363364 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;365366 367 match target_collection.mode 368 {369 CollectionMode::NFT(_) => {370 371 let item = NftItemType {372 collection: collection_id,373 owner: owner,374 data: properties.clone(),375 };376 377 Self::add_nft_item(item)?;378 379 },380 CollectionMode::ReFungible(_, _) => {381 let mut owner_list = Vec::new();382 let value = (10 as u128).pow(target_collection.decimal_points);383 owner_list.push(Ownership {owner: owner.clone(), fraction: value});384385 let item = ReFungibleItemType {386 collection: collection_id,387 owner: owner_list,388 data: properties.clone()389 };390 391 Self::add_refungible_item(item)?;392 },393 _ => { ensure!(1 == 0,"just error"); }394395 };396397 398 Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));399400 Ok(())401 }402403 #[weight = 0]404 pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {405406 let sender = ensure_signed(origin)?;407 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);408 if !item_owner409 {410 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;411 }412 let target_collection = <Collection<T>>::get(collection_id);413414 match target_collection.mode 415 {416 CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,417 CollectionMode::ReFungible(_, _) => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,418 _ => ()419 };420421 422 Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));423424 Ok(())425 }426427 #[weight = 0]428 pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {429430 let sender = ensure_signed(origin)?;431 ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");432433 let target_collection = <Collection<T>>::get(collection_id);434435 436 match target_collection.mode 437 {438 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,439 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,440 _ => ()441 };442443 Ok(())444 }445446 #[weight = 0]447 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {448449 let sender = ensure_signed(origin)?;450451 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);452 if !item_owner453 {454 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;455 }456457 let list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);458 if list_exists {459460 let mut list = <ApprovedList<T>>::get(collection_id, item_id);461 let item_contains = list.contains(&approved.clone());462463 if !item_contains {464 list.push(approved.clone());465 }466 } else {467468 let mut itm = Vec::new();469 itm.push(approved.clone());470 <ApprovedList<T>>::insert(collection_id, item_id, itm);471 }472473 Ok(())474 }475476 #[weight = 0]477 pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {478479 let mut approved: bool = false; 480 let sender = ensure_signed(origin)?;481 let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);482 if approved_list_exists483 {484 let list_itm = <ApprovedList<T>>::get(collection_id, item_id);485 approved = list_itm.contains(&recipient.clone());486 }487488 if !approved489 {490 Self::check_owner_or_admin_permissions(collection_id, sender)?;491 }492 493 let target_collection = <Collection<T>>::get(collection_id);494495 match target_collection.mode496 {497 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,498 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, from, recipient)?,499 500 _ => ()501 };502503 Ok(())504 }505506 #[weight = 0]507 pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {508509 510 511 512 513514 515516 517518 Ok(())519 }520521 #[weight = 0]522 pub fn set_offchain_schema(523 origin,524 collection_id: u64,525 schema: Vec<u8>526 ) -> DispatchResult {527 let sender = ensure_signed(origin)?;528 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;529 530 let mut target_collection = <Collection<T>>::get(collection_id);531 target_collection.offchain_schema = schema;532 <Collection<T>>::insert(collection_id, target_collection);533534 Ok(()) 535 }536 }537}538539impl<T: Trait> Module<T> {540541 fn collection_exists(collection_id: u64) -> DispatchResult{542 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");543 Ok(())544 }545546 fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {547548 Self::collection_exists(collection_id)?;549550 let target_collection = <Collection<T>>::get(collection_id);551 ensure!(subject == target_collection.owner, "You do not own this collection");552553 Ok(())554 }555556 fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {557558 Self::collection_exists(collection_id)?;559560 let target_collection = <Collection<T>>::get(collection_id);561 let is_owner = subject == target_collection.owner;562563 let no_perm_mes = "You do not have permissions to modify this collection";564 let exists = <AdminList<T>>::contains_key(collection_id);565566 if !is_owner567 {568 ensure!(exists, no_perm_mes);569 ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);570 }571 Ok(())572 }573574 fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{575576 let target_collection = <Collection<T>>::get(collection_id);577578 match target_collection.mode {579 CollectionMode::NFT(_) => <NftItemList<T>>::get(collection_id, item_id).owner == subject,580 CollectionMode::Fungible(_) => <FungibleItemList<T>>::get(collection_id, item_id).owner == subject,581 CollectionMode::ReFungible(_, _) => <ReFungibleItemList<T>>::get(collection_id, item_id).owner.iter().any(|i| i.owner == subject),582 CollectionMode::Invalid => false583 }584 }585586 fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {587588 let current_index = <ItemListIndex>::get(item.collection)589 .checked_add(1)590 .expect("Item list index id error");591 let itemcopy = item.clone();592593 let value = item.owner.first().unwrap().fraction as u64;594 let owner = item.owner.first().unwrap().owner.clone();595596 Self::add_token_index(item.collection, current_index, owner.clone())?;597598 <ItemListIndex>::insert(item.collection, current_index);599 <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy); 600 601 602 let new_balance = <Balance<T>>::get(item.collection, owner.clone()).checked_add(value).unwrap();603 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);604605 Ok(())606 }607608 fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {609 610 let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);611 let item = collection.owner.iter().filter(|&i| i.owner == owner).next().unwrap();612 Self::remove_token_index(collection_id, item_id, owner)?;613614 615 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(item.fraction as u64).unwrap();616 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);617618 619 <ReFungibleItemList<T>>::remove(collection_id, item_id);620621 Ok(())622 }623624 fn transfer_refungible(collection_id: u64, item_id: u64, value: u64, owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {625626 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);627 let item = full_item.owner.iter().filter(|i| i.owner == owner).next().unwrap();628 let amount = item.fraction;629630 ensure!(amount >= value.into(),"Item balance not enouth");631632 633 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(value).unwrap();634 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);635636 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();637 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);638639 let old_owner = item.owner.clone();640 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);641 let val64 = value.into();642643 644 if amount == val64 && !new_owner_has_account645 {646 647 648 let mut new_full_item = full_item.clone();649 new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().owner = new_owner.clone();650 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);651652 653 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;654 }655 else656 {657 let mut new_full_item = full_item.clone();658 new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().fraction -= val64;659660 661 if new_owner_has_account {662 663 new_full_item.owner.iter_mut().find(|i| i.owner == new_owner).unwrap().fraction += val64;664 }665 else666 {667 668 new_full_item.owner.push(Ownership { owner: new_owner.clone(), fraction: val64});669 Self::add_token_index(collection_id, item_id, new_owner.clone())?;670 }671672 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);673 }674675 Ok(())676 }677 678 fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {679680 let current_index = <ItemListIndex>::get(item.collection)681 .checked_add(1)682 .expect("Item list index id error");683 let itemcopy = item.clone();684685 Self::add_token_index(item.collection, current_index, item.owner.clone())?;686687 <ItemListIndex>::insert(item.collection, current_index);688 <NftItemList<T>>::insert(item.collection, current_index, item);689690 691 let new_balance = <Balance<T>>::get(itemcopy.collection, itemcopy.owner.clone()).checked_add(1).unwrap();692 <Balance<T>>::insert(itemcopy.collection, itemcopy.owner.clone(), new_balance);693694 Ok(())695 }696697 fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {698 699 let item = <NftItemList<T>>::get(collection_id, item_id);700 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;701702 703 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();704 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);705 <NftItemList<T>>::remove(collection_id, item_id);706707 Ok(())708 }709710 fn transfer_nft(collection_id: u64, item_id: u64, sender: T::AccountId, new_owner: T::AccountId) -> DispatchResult {711712 let mut item = <NftItemList<T>>::get(collection_id, item_id);713714 ensure!(sender == item.owner,"sender parameter and item owner must be equal");715716 717 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();718 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);719720 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();721 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);722723 724 let old_owner = item.owner.clone();725 item.owner = new_owner.clone();726 <NftItemList<T>>::insert(collection_id, item_id, item);727728 729 Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;730731 732 let itm: Vec<T::AccountId> = Vec::new();733 <ApprovedList<T>>::insert(collection_id, item_id, itm);734735 Ok(())736 }737738 fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {739 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());740 if list_exists {741 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());742 let item_contains = list.contains(&item_index.clone());743744 if !item_contains {745 list.push(item_index.clone());746 }747748 <AddressTokens<T>>::insert(collection_id, owner.clone(), list);749 } else {750 let mut itm = Vec::new();751 itm.push(item_index.clone());752 <AddressTokens<T>>::insert(collection_id, owner, itm);753 }754755 Ok(())756 }757758 fn remove_token_index(759 collection_id: u64,760 item_index: u64,761 owner: T::AccountId,762 ) -> DispatchResult {763 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());764 if list_exists {765 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());766 let item_contains = list.contains(&item_index.clone());767768 if item_contains {769 list.retain(|&item| item != item_index);770 <AddressTokens<T>>::insert(collection_id, owner, list);771 }772 }773774 Ok(())775 }776777 fn move_token_index(778 collection_id: u64,779 item_index: u64,780 old_owner: T::AccountId,781 new_owner: T::AccountId,782 ) -> DispatchResult {783 Self::remove_token_index(collection_id, item_index, old_owner)?;784 Self::add_token_index(collection_id, item_index, new_owner)?;785786 Ok(())787 }788}789790791792793794795pub type Multiplier = FixedU128;796797type BalanceOf<T> =798 <<T as transaction_payment::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;799type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<800 <T as system::Trait>::AccountId,>>::NegativeImbalance;801802803804805806#[derive(Encode, Decode, Clone, Eq, PartialEq)]807pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(#[codec(compact)] BalanceOf<T>);808809impl<T:Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug for ChargeTransactionPayment<T> {810 #[cfg(feature = "std")]811 fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {812 write!(f, "ChargeTransactionPayment<{:?}>", self.0)813 }814 #[cfg(not(feature = "std"))]815 fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {816 Ok(())817 }818}819820impl<T:Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T> where821 T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,822 BalanceOf<T>: Send + Sync + FixedPointOperand,823{824 825 pub fn from(fee: BalanceOf<T>) -> Self {826 Self(fee)827 }828829 pub fn traditional_fee(830 len: usize,831 info: &DispatchInfoOf<T::Call>,832 tip: BalanceOf<T>,833 ) -> BalanceOf<T> where834 T::Call: Dispatchable<Info=DispatchInfo>,835 {836 <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)837 }838839 fn withdraw_fee(840 &self,841 who: &T::AccountId,842 call: &T::Call,843 info: &DispatchInfoOf<T::Call>,844 len: usize,845 ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {846 let tip = self.0;847848 849 850 let fee = match call.is_sub_type() {851 Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),852 _ => Self::traditional_fee(len, info, tip)853854 855 856 };857858 859 860 let sponsor: T::AccountId = match call.is_sub_type() {861 Some(Call::create_item(collection_id, _properties, _owner)) => {862 <Collection<T>>::get(collection_id).sponsor863 },864 Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {865 <Collection<T>>::get(collection_id).sponsor866 },867868 _ => T::AccountId::default()869 };870871 let mut who_pays_fee: T::AccountId = sponsor.clone();872 if sponsor == T::AccountId::default() {873 who_pays_fee = who.clone();874 }875876 877 if fee.is_zero() {878 return Ok((fee, None));879 }880881 match <T as transaction_payment::Trait>::Currency::withdraw(882 &who_pays_fee,883 fee,884 if tip.is_zero() {885 WithdrawReason::TransactionPayment.into()886 } else {887 WithdrawReason::TransactionPayment | WithdrawReason::Tip888 },889 ExistenceRequirement::KeepAlive,890 ) {891 Ok(imbalance) => Ok((fee, Some(imbalance))),892 Err(_) => Err(InvalidTransaction::Payment.into()),893 }894 }895}896897impl<T:Trait + transaction_payment::Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> where898 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,899 T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,900{901 const IDENTIFIER: &'static str = "ChargeTransactionPayment";902 type AccountId = T::AccountId;903 type Call = T::Call;904 type AdditionalSigned = ();905 type Pre = (BalanceOf<T>, Self::AccountId, Option<NegativeImbalanceOf<T>>, BalanceOf<T>);906 fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { Ok(()) }907908 fn validate(909 &self,910 who: &Self::AccountId,911 call: &Self::Call,912 info: &DispatchInfoOf<Self::Call>,913 len: usize,914 ) -> TransactionValidity {915 let (fee, _) = self.withdraw_fee(who, call, info, len)?;916917 let mut r = ValidTransaction::default();918 919 920 r.priority = fee.saturated_into::<TransactionPriority>();921 Ok(r)922 }923924 fn pre_dispatch(925 self,926 who: &Self::AccountId,927 call: &Self::Call,928 info: &DispatchInfoOf<Self::Call>,929 len: usize930 ) -> Result<Self::Pre, TransactionValidityError> {931 let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;932 Ok((self.0, who.clone(), imbalance, fee))933 }934935 fn post_dispatch(936 pre: Self::Pre,937 info: &DispatchInfoOf<Self::Call>,938 post_info: &PostDispatchInfoOf<Self::Call>,939 len: usize,940 _result: &DispatchResult,941 ) -> Result<(), TransactionValidityError> {942 let (tip, who, imbalance, fee) = pre;943 if let Some(payed) = imbalance {944 let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(945 len as u32,946 info,947 post_info,948 tip,949 );950 let refund = fee.saturating_sub(actual_fee);951 let actual_payment = match <T as transaction_payment::Trait>::Currency::deposit_into_existing(&who, refund) {952 Ok(refund_imbalance) => {953 954 955 match payed.offset(refund_imbalance) {956 Ok(actual_payment) => actual_payment,957 Err(_) => return Err(InvalidTransaction::Payment.into()),958 }959 }960 961 962 Err(_) => payed,963 };964 let imbalances = actual_payment.split(tip);965 <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(Some(imbalances.0).into_iter()966 .chain(Some(imbalances.1)));967 }968 Ok(())969 }970}