difftreelog
Add sponsorship methods + transfer refactoring
in: master
1 file changed
pallets/nft/src/lib.rsdiffbeforeafterboth1#![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 size48 ReFungible(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 next_item_id: u64,85 pub decimal_points: u32,86 pub name: Vec<u16>, // 64 include null escape char87 pub description: Vec<u16>, // 256 include null escape char88 pub token_prefix: Vec<u8>, // 16 include null escape char89 pub custom_data_size: u32,90 pub offchain_schema: Vec<u8>,91 pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender92 pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship93}9495#[derive(Encode, Decode, Default, Clone, PartialEq)]96#[cfg_attr(feature = "std", derive(Debug))]97pub struct CollectionAdminsType<AccountId> {98 pub admin: AccountId,99 pub collection_id: u64,100}101102#[derive(Encode, Decode, Default, Clone, PartialEq)]103#[cfg_attr(feature = "std", derive(Debug))]104pub struct NftItemType<AccountId> {105 pub collection: u64,106 pub owner: AccountId,107 pub data: Vec<u8>,108}109110#[derive(Encode, Decode, Default, Clone, PartialEq)]111#[cfg_attr(feature = "std", derive(Debug))]112pub struct FungibleItemType<AccountId> {113 pub collection: u64,114 pub owner: AccountId,115 pub value: u128,116}117118#[derive(Encode, Decode, Default, Clone, PartialEq)]119#[cfg_attr(feature = "std", derive(Debug))]120pub struct ReFungibleItemType<AccountId> {121 pub collection: u64,122 pub owner: Vec<Ownership<AccountId>>,123 pub data: Vec<u8>,124}125126pub trait Trait: system::Trait {127 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;128129}130131decl_storage! {132 trait Store for Module<T: Trait> as Nft {133134 // Private members135 NextCollectionID: u64;136 ItemListIndex: map hasher(blake2_128_concat) u64 => u64;137138 pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;139 pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;140 pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;141142 // Balance owner per collection map143 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;144 pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => Vec<T::AccountId>;145146 // Item collections147 pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;148 pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;149 pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;150151 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;152 }153}154155decl_event!(156 pub enum Event<T>157 where158 AccountId = <T as system::Trait>::AccountId,159 {160 Created(u64, u8, AccountId),161 ItemCreated(u64, u64),162 ItemDestroyed(u64, u64),163 }164);165166decl_module! {167 pub struct Module<T: Trait> for enum Call where origin: T::Origin {168169 fn deposit_event() = default;170171 // Create collection of NFT with given parameters172 //173 // @param customDataSz size of custom data in each collection item174 // returns collection ID175 #[weight = 0]176 pub fn create_collection( origin,177 collection_name: Vec<u16>,178 collection_description: Vec<u16>,179 token_prefix: Vec<u8>,180 mode: CollectionMode) -> DispatchResult {181182 // Anyone can create a collection183 let who = ensure_signed(origin)?;184 let custom_data_size = match mode {185 CollectionMode::NFT(size) => size,186 CollectionMode::ReFungible(size) => size,187 _ => 0188 };189190 let decimal_points = match mode {191 CollectionMode::Fungible(points) => points,192 _ => 0193 };194195 // check params196 ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4"); 197198 let mut name = collection_name.to_vec();199 name.push(0);200 ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");201202 let mut description = collection_description.to_vec();203 description.push(0);204 ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");205206 let mut prefix = token_prefix.to_vec();207 prefix.push(0);208 ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");209210 // Generate next collection ID211 let next_id = NextCollectionID::get()212 .checked_add(1)213 .expect("collection id error");214215 NextCollectionID::put(next_id);216217 // Create new collection218 let new_collection = CollectionType {219 owner: who.clone(),220 name: name,221 mode: mode.clone(),222 access: AccessMode::Normal,223 description: description,224 decimal_points: decimal_points,225 token_prefix: prefix,226 next_item_id: next_id,227 offchain_schema: Vec::new(),228 custom_data_size: custom_data_size,229 sponsor: T::AccountId::default(),230 unconfirmed_sponsor: T::AccountId::default(),231 };232233 // Add new collection to map234 <Collection<T>>::insert(next_id, new_collection);235236 // call event237 Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));238239 Ok(())240 }241242 #[weight = 0]243 pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {244245 let sender = ensure_signed(origin)?;246 Self::check_owner_permissions(collection_id, sender)?;247248 <AddressTokens<T>>::remove_prefix(collection_id);249 <ApprovedList<T>>::remove_prefix(collection_id);250 <Balance<T>>::remove_prefix(collection_id);251 <ItemListIndex>::remove(collection_id);252 <AdminList<T>>::remove(collection_id);253 <Collection<T>>::remove(collection_id);254 <WhiteList<T>>::remove(collection_id);255256 Ok(())257 }258259 #[weight = 0]260 pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {261262 let sender = ensure_signed(origin)?;263 Self::check_owner_permissions(collection_id, sender)?;264 let mut target_collection = <Collection<T>>::get(collection_id);265 target_collection.owner = new_owner;266 <Collection<T>>::insert(collection_id, target_collection);267268 Ok(())269 }270271 #[weight = 0]272 pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {273274 let sender = ensure_signed(origin)?;275 Self::check_owner_or_admin_permissions(collection_id, sender)?;276 let mut admin_arr: Vec<T::AccountId> = Vec::new();277278 if <AdminList<T>>::contains_key(collection_id)279 {280 admin_arr = <AdminList<T>>::get(collection_id);281 ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");282 }283284 admin_arr.push(new_admin_id);285 <AdminList<T>>::insert(collection_id, admin_arr);286287 Ok(())288 }289290 #[weight = 0]291 pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {292293 let sender = ensure_signed(origin)?;294 Self::check_owner_or_admin_permissions(collection_id, sender)?;295296 if <AdminList<T>>::contains_key(collection_id)297 {298 let mut admin_arr = <AdminList<T>>::get(collection_id);299 admin_arr.retain(|i| *i != account_id);300 <AdminList<T>>::insert(collection_id, admin_arr);301 }302303 Ok(())304 }305306 #[weight = 0]307 pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {308309 let sender = ensure_signed(origin)?;310 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");311312 let mut target_collection = <Collection<T>>::get(collection_id);313 ensure!(sender == target_collection.owner, "You do not own this collection");314315 target_collection.unconfirmed_sponsor = new_sponsor;316 <Collection<T>>::insert(collection_id, target_collection);317318 Ok(())319 }320321 #[weight = 0]322 pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {323324 let sender = ensure_signed(origin)?;325 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");326327 let mut target_collection = <Collection<T>>::get(collection_id);328 ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");329330 target_collection.sponsor = target_collection.unconfirmed_sponsor;331 target_collection.unconfirmed_sponsor = T::AccountId::default();332 <Collection<T>>::insert(collection_id, target_collection);333334 Ok(())335 }336337 #[weight = 0]338 pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {339340 let sender = ensure_signed(origin)?;341 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");342343 let mut target_collection = <Collection<T>>::get(collection_id);344 ensure!(sender == target_collection.owner, "You do not own this collection");345346 target_collection.sponsor = T::AccountId::default();347 <Collection<T>>::insert(collection_id, target_collection);348349 Ok(())350 }351 352 #[weight = 0]353 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {354355 let sender = ensure_signed(origin)?;356357 // check size358 let target_collection = <Collection<T>>::get(collection_id);359 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");360361 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;362363 let new_balance = <Balance<T>>::get(collection_id, owner.clone()).checked_add(1).unwrap();364 <Balance<T>>::insert(collection_id, owner.clone(), new_balance);365366 // TODO: implement other modes367 match target_collection.mode 368 {369 CollectionMode::NFT(_) => {370 // Create nft item371 let item = NftItemType {372 collection: collection_id,373 owner: owner,374 data: properties,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, fraction: value});384385 let item = ReFungibleItemType {386 collection: collection_id,387 owner: owner_list,388 data: properties389 };390 391 Self::add_refungible_item(item)?;392 },393 _ => ()394 };395396 // call event397 Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));398399 Ok(())400 }401402 #[weight = 0]403 pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {404405 let sender = ensure_signed(origin)?;406 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);407 if !item_owner408 {409 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;410 }411 let target_collection = <Collection<T>>::get(collection_id);412413 match target_collection.mode 414 {415 CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,416 CollectionMode::ReFungible(_) => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,417 _ => ()418 };419420 // call event421 Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));422423 Ok(())424 }425426 #[weight = 0]427 pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {428429 let sender = ensure_signed(origin)?;430 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);431 if !item_owner432 {433 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;434 }435436 let target_collection = <Collection<T>>::get(collection_id);437438 // TODO: implement other modes439 match target_collection.mode 440 {441 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, recipient)?,442 CollectionMode::ReFungible(_) => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,443 _ => ()444 };445446 Ok(())447 }448449 #[weight = 0]450 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {451452 let sender = ensure_signed(origin)?;453454 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);455 if !item_owner456 {457 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;458 }459460 let list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);461 if list_exists {462463 let mut list = <ApprovedList<T>>::get(collection_id, item_id);464 let item_contains = list.contains(&approved.clone());465466 if !item_contains {467 list.push(approved.clone());468 }469 } else {470471 let mut itm = Vec::new();472 itm.push(approved.clone());473 <ApprovedList<T>>::insert(collection_id, item_id, itm);474 }475476 Ok(())477 }478479 #[weight = 0]480 pub fn transfer_from(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, ) -> DispatchResult {481482 let mut approved: bool = false; 483 let sender = ensure_signed(origin)?;484 let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);485 if approved_list_exists486 {487 let list_itm = <ApprovedList<T>>::get(collection_id, item_id);488 approved = list_itm.contains(&recipient.clone());489 }490491 if !approved492 {493 Self::check_owner_or_admin_permissions(collection_id, sender)?;494 }495 496 let target_collection = <Collection<T>>::get(collection_id);497498 match target_collection.mode499 {500 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, recipient)?,501 // TODO: implement other modes502 _ => ()503 };504505 Ok(())506 }507508 #[weight = 0]509 pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {510511 // let no_perm_mes = "You do not have permissions to modify this collection";512 // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);513 // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));514 // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);515516 // // on_nft_received call517518 // Self::transfer(origin, collection_id, item_id, new_owner)?;519520 Ok(())521 }522523 #[weight = 0]524 pub fn set_offchain_schema(525 origin,526 collection_id: u64,527 schema: Vec<u8>528 ) -> DispatchResult {529 let sender = ensure_signed(origin)?;530 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;531 532 let mut target_collection = <Collection<T>>::get(collection_id);533 target_collection.offchain_schema = schema;534 <Collection<T>>::insert(collection_id, target_collection);535536 Ok(()) 537 }538 }539}540541impl<T: Trait> Module<T> {542543 fn collection_exists(collection_id: u64) -> DispatchResult{544 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");545 Ok(())546 }547548 fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {549550 Self::collection_exists(collection_id)?;551552 let target_collection = <Collection<T>>::get(collection_id);553 ensure!(subject == target_collection.owner, "You do not own this collection");554555 Ok(())556 }557558 fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {559560 Self::collection_exists(collection_id)?;561562 let target_collection = <Collection<T>>::get(collection_id);563 let is_owner = subject == target_collection.owner;564565 let no_perm_mes = "You do not have permissions to modify this collection";566 let exists = <AdminList<T>>::contains_key(collection_id);567568 if !is_owner569 {570 ensure!(exists, no_perm_mes);571 ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);572 }573 Ok(())574 }575576 fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{577578 let target_collection = <Collection<T>>::get(collection_id);579580 match target_collection.mode {581 CollectionMode::NFT(_) => <NftItemList<T>>::get(collection_id, item_id).owner == subject,582 CollectionMode::Fungible(_) => <FungibleItemList<T>>::get(collection_id, item_id).owner == subject,583 CollectionMode::ReFungible(_) => <ReFungibleItemList<T>>::get(collection_id, item_id).owner.iter().any(|i| i.owner == subject),584 CollectionMode::Invalid => false585 }586 }587588 fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {589590 let current_index = <ItemListIndex>::get(item.collection)591 .checked_add(1)592 .expect("Item list index id error");593594 Self::add_token_index(item.collection, current_index, item.owner.first().unwrap().owner.clone())?;595596 <ItemListIndex>::insert(item.collection, current_index);597 <ReFungibleItemList<T>>::insert(item.collection, current_index, item); 598599 Ok(())600 }601602 fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {603 604 let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);605 let item = collection.owner.iter().filter(|&i| i.owner == owner).next().unwrap();606 Self::remove_token_index(collection_id, item_id, owner)?;607608 // update balance609 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(item.fraction as u64).unwrap();610 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);611612 // TODO613 <ReFungibleItemList<T>>::remove(collection_id, item_id);614615 Ok(())616 }617618 fn transfer_refungible(collection_id: u64, item_id: u64, value: u64, owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {619620 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);621 let item = full_item.owner.iter().filter(|i| i.owner == owner).next().unwrap();622 let amount = item.fraction;623624 ensure!(amount < value.into(),"Item balance not enouth");625626 // update balance627 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(value).unwrap();628 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);629630 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();631 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);632633 let old_owner = item.owner.clone();634 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);635636 // transfer637 if amount == value.into() && !new_owner_has_account638 {639 // change owner640 // new owner do not have account641 let mut new_full_item = full_item.clone();642 new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().owner = new_owner.clone();643 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);644645 // update index collection646 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;647 }648 else649 {650 let mut new_full_item = full_item.clone();651 new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().fraction -= amount;652653 // separate amount654 if new_owner_has_account {655 // new owner has account656 new_full_item.owner.iter_mut().find(|i| i.owner == new_owner).unwrap().fraction += amount;657 }658 else659 {660 // new owner do not have account661 new_full_item.owner.push(Ownership { owner: new_owner.clone(), fraction: amount});662 Self::add_token_index(collection_id, item_id, new_owner.clone())?;663 }664665 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);666 }667668 Ok(())669 }670 671 fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {672673 let current_index = <ItemListIndex>::get(item.collection)674 .checked_add(1)675 .expect("Item list index id error");676677 Self::add_token_index(item.collection, current_index, item.owner.clone())?;678679 <ItemListIndex>::insert(item.collection, current_index);680 <NftItemList<T>>::insert(item.collection, current_index, item);681682 Ok(())683 }684685 fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {686 687 let item = <NftItemList<T>>::get(collection_id, item_id);688 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;689690 // update balance691 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();692 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);693 <NftItemList<T>>::remove(collection_id, item_id);694695 Ok(())696 }697698 fn transfer_nft(collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {699700 let mut item = <NftItemList<T>>::get(collection_id, item_id);701702 // update balance703 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();704 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);705706 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();707 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);708709 // change owner710 let old_owner = item.owner.clone();711 item.owner = new_owner.clone();712 <NftItemList<T>>::insert(collection_id, item_id, item);713714 // update index collection715 Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;716717 // reset approved list718 let itm: Vec<T::AccountId> = Vec::new();719 <ApprovedList<T>>::insert(collection_id, item_id, itm);720721 Ok(())722 }723724 fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {725 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());726 if list_exists {727 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());728 let item_contains = list.contains(&item_index.clone());729730 if !item_contains {731 list.push(item_index.clone());732 }733734 <AddressTokens<T>>::insert(collection_id, owner.clone(), list);735 } else {736 let mut itm = Vec::new();737 itm.push(item_index.clone());738 <AddressTokens<T>>::insert(collection_id, owner, itm);739 }740741 Ok(())742 }743744 fn remove_token_index(745 collection_id: u64,746 item_index: u64,747 owner: T::AccountId,748 ) -> DispatchResult {749 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());750 if list_exists {751 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());752 let item_contains = list.contains(&item_index.clone());753754 if item_contains {755 list.retain(|&item| item != item_index);756 <AddressTokens<T>>::insert(collection_id, owner, list);757 }758 }759760 Ok(())761 }762763 fn move_token_index(764 collection_id: u64,765 item_index: u64,766 old_owner: T::AccountId,767 new_owner: T::AccountId,768 ) -> DispatchResult {769 Self::remove_token_index(collection_id, item_index, old_owner)?;770 Self::add_token_index(collection_id, item_index, new_owner)?;771772 Ok(())773 }774}775776777////////////////////////////////////////////////////////////////////////////////////////////////////778// Economic models779780/// Fee multiplier.781pub type Multiplier = FixedU128;782783type BalanceOf<T> =784 <<T as transaction_payment::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;785type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<786 <T as system::Trait>::AccountId,>>::NegativeImbalance;787788789790/// Require the transactor pay for themselves and maybe include a tip to gain additional priority791/// in the queue.792#[derive(Encode, Decode, Clone, Eq, PartialEq)]793pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(#[codec(compact)] BalanceOf<T>);794795impl<T:Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug for ChargeTransactionPayment<T> {796 #[cfg(feature = "std")]797 fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {798 write!(f, "ChargeTransactionPayment<{:?}>", self.0)799 }800 #[cfg(not(feature = "std"))]801 fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {802 Ok(())803 }804}805806impl<T:Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T> where807 T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,808 BalanceOf<T>: Send + Sync + FixedPointOperand,809{810 /// utility constructor. Used only in client/factory code.811 pub fn from(fee: BalanceOf<T>) -> Self {812 Self(fee)813 }814815 pub fn traditional_fee(816 len: usize,817 info: &DispatchInfoOf<T::Call>,818 tip: BalanceOf<T>,819 ) -> BalanceOf<T> where820 T::Call: Dispatchable<Info=DispatchInfo>,821 {822 <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)823 }824825 fn withdraw_fee(826 &self,827 who: &T::AccountId,828 call: &T::Call,829 info: &DispatchInfoOf<T::Call>,830 len: usize,831 ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {832 let tip = self.0;833834 // Set fee based on call type. Creating collection costs 1 Unique.835 // All other transactions have traditional fees so far836 let fee = match call.is_sub_type() {837 Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),838 _ => Self::traditional_fee(len, info, tip)839840 // Flat fee model, use only for testing purposes841 // _ => <BalanceOf<T>>::from(100)842 };843844 // Determine who is paying transaction fee based on ecnomic model845 // Parse call to extract collection ID and access collection sponsor846 let sponsor: T::AccountId = match call.is_sub_type() {847 Some(Call::create_item(collection_id, _properties, _owner)) => {848 <Collection<T>>::get(collection_id).sponsor849 },850 Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {851 <Collection<T>>::get(collection_id).sponsor852 },853854 _ => T::AccountId::default()855 };856857 let mut who_pays_fee: T::AccountId = sponsor.clone();858 if sponsor == T::AccountId::default() {859 who_pays_fee = who.clone();860 }861862 // Only mess with balances if fee is not zero.863 if fee.is_zero() {864 return Ok((fee, None));865 }866867 match <T as transaction_payment::Trait>::Currency::withdraw(868 &who_pays_fee,869 fee,870 if tip.is_zero() {871 WithdrawReason::TransactionPayment.into()872 } else {873 WithdrawReason::TransactionPayment | WithdrawReason::Tip874 },875 ExistenceRequirement::KeepAlive,876 ) {877 Ok(imbalance) => Ok((fee, Some(imbalance))),878 Err(_) => Err(InvalidTransaction::Payment.into()),879 }880 }881}882883impl<T:Trait + transaction_payment::Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> where884 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,885 T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,886{887 const IDENTIFIER: &'static str = "ChargeTransactionPayment";888 type AccountId = T::AccountId;889 type Call = T::Call;890 type AdditionalSigned = ();891 type Pre = (BalanceOf<T>, Self::AccountId, Option<NegativeImbalanceOf<T>>, BalanceOf<T>);892 fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { Ok(()) }893894 fn validate(895 &self,896 who: &Self::AccountId,897 call: &Self::Call,898 info: &DispatchInfoOf<Self::Call>,899 len: usize,900 ) -> TransactionValidity {901 let (fee, _) = self.withdraw_fee(who, call, info, len)?;902903 let mut r = ValidTransaction::default();904 // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which905 // will be a bit more than setting the priority to tip. For now, this is enough.906 r.priority = fee.saturated_into::<TransactionPriority>();907 Ok(r)908 }909910 fn pre_dispatch(911 self,912 who: &Self::AccountId,913 call: &Self::Call,914 info: &DispatchInfoOf<Self::Call>,915 len: usize916 ) -> Result<Self::Pre, TransactionValidityError> {917 let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;918 Ok((self.0, who.clone(), imbalance, fee))919 }920921 fn post_dispatch(922 pre: Self::Pre,923 info: &DispatchInfoOf<Self::Call>,924 post_info: &PostDispatchInfoOf<Self::Call>,925 len: usize,926 _result: &DispatchResult,927 ) -> Result<(), TransactionValidityError> {928 let (tip, who, imbalance, fee) = pre;929 if let Some(payed) = imbalance {930 let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(931 len as u32,932 info,933 post_info,934 tip,935 );936 let refund = fee.saturating_sub(actual_fee);937 let actual_payment = match <T as transaction_payment::Trait>::Currency::deposit_into_existing(&who, refund) {938 Ok(refund_imbalance) => {939 // The refund cannot be larger than the up front payed max weight.940 // `PostDispatchInfo::calc_unspent` guards against such a case.941 match payed.offset(refund_imbalance) {942 Ok(actual_payment) => actual_payment,943 Err(_) => return Err(InvalidTransaction::Payment.into()),944 }945 }946 // We do not recreate the account using the refund. The up front payment947 // is gone in that case.948 Err(_) => payed,949 };950 let imbalances = actual_payment.split(tip);951 <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(Some(imbalances.0).into_iter()952 .chain(Some(imbalances.1)));953 }954 Ok(())955 }956}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 next_item_id: u64,85 pub decimal_points: u32,86 pub name: Vec<u16>, // 64 include null escape char87 pub description: Vec<u16>, // 256 include null escape char88 pub token_prefix: Vec<u8>, // 16 include null escape char89 pub custom_data_size: u32,90 pub offchain_schema: Vec<u8>,91 pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender92 pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship93}9495#[derive(Encode, Decode, Default, Clone, PartialEq)]96#[cfg_attr(feature = "std", derive(Debug))]97pub struct CollectionAdminsType<AccountId> {98 pub admin: AccountId,99 pub collection_id: u64,100}101102#[derive(Encode, Decode, Default, Clone, PartialEq)]103#[cfg_attr(feature = "std", derive(Debug))]104pub struct NftItemType<AccountId> {105 pub collection: u64,106 pub owner: AccountId,107 pub data: Vec<u8>,108}109110#[derive(Encode, Decode, Default, Clone, PartialEq)]111#[cfg_attr(feature = "std", derive(Debug))]112pub struct FungibleItemType<AccountId> {113 pub collection: u64,114 pub owner: AccountId,115 pub value: u128,116}117118#[derive(Encode, Decode, Default, Clone, PartialEq)]119#[cfg_attr(feature = "std", derive(Debug))]120pub struct ReFungibleItemType<AccountId> {121 pub collection: u64,122 pub owner: Vec<Ownership<AccountId>>,123 pub data: Vec<u8>,124}125126pub trait Trait: system::Trait {127 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;128129}130131decl_storage! {132 trait Store for Module<T: Trait> as Nft {133134 // Private members135 NextCollectionID: u64;136 ItemListIndex: map hasher(blake2_128_concat) u64 => u64;137138 pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;139 pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;140 pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;141142 // Balance owner per collection map143 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;144 pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => Vec<T::AccountId>;145146 // Item collections147 pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;148 pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;149 pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;150151 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;152153 // Sponsorship154 pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;155 pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;156 }157}158159decl_event!(160 pub enum Event<T>161 where162 AccountId = <T as system::Trait>::AccountId,163 {164 Created(u64, u8, AccountId),165 ItemCreated(u64, u64),166 ItemDestroyed(u64, u64),167 }168);169170decl_module! {171 pub struct Module<T: Trait> for enum Call where origin: T::Origin {172173 fn deposit_event() = default;174175 // Create collection of NFT with given parameters176 //177 // @param customDataSz size of custom data in each collection item178 // returns collection ID179 #[weight = 0]180 pub fn create_collection( origin,181 collection_name: Vec<u16>,182 collection_description: Vec<u16>,183 token_prefix: Vec<u8>,184 mode: CollectionMode) -> DispatchResult {185186 // Anyone can create a collection187 let who = ensure_signed(origin)?;188 let custom_data_size = match mode {189 CollectionMode::NFT(size) => size,190 CollectionMode::ReFungible(size, _) => size,191 _ => 0192 };193194 let decimal_points = match mode {195 CollectionMode::Fungible(points) => points,196 CollectionMode::ReFungible(_, points) => points,197 _ => 0198 };199200 // check params201 ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4"); 202203 let mut name = collection_name.to_vec();204 name.push(0);205 ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");206207 let mut description = collection_description.to_vec();208 description.push(0);209 ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");210211 let mut prefix = token_prefix.to_vec();212 prefix.push(0);213 ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");214215 // Generate next collection ID216 let next_id = NextCollectionID::get()217 .checked_add(1)218 .expect("collection id error");219220 NextCollectionID::put(next_id);221222 // Create new collection223 let new_collection = CollectionType {224 owner: who.clone(),225 name: name,226 mode: mode.clone(),227 access: AccessMode::Normal,228 description: description,229 decimal_points: decimal_points,230 token_prefix: prefix,231 next_item_id: next_id,232 offchain_schema: Vec::new(),233 custom_data_size: custom_data_size,234 sponsor: T::AccountId::default(),235 unconfirmed_sponsor: T::AccountId::default(),236 };237238 // Add new collection to map239 <Collection<T>>::insert(next_id, new_collection);240241 // call event242 Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));243244 Ok(())245 }246247 #[weight = 0]248 pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {249250 let sender = ensure_signed(origin)?;251 Self::check_owner_permissions(collection_id, sender)?;252253 <AddressTokens<T>>::remove_prefix(collection_id);254 <ApprovedList<T>>::remove_prefix(collection_id);255 <Balance<T>>::remove_prefix(collection_id);256 <ItemListIndex>::remove(collection_id);257 <AdminList<T>>::remove(collection_id);258 <Collection<T>>::remove(collection_id);259 <WhiteList<T>>::remove(collection_id);260261 Ok(())262 }263264 #[weight = 0]265 pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {266267 let sender = ensure_signed(origin)?;268 Self::check_owner_permissions(collection_id, sender)?;269 let mut target_collection = <Collection<T>>::get(collection_id);270 target_collection.owner = new_owner;271 <Collection<T>>::insert(collection_id, target_collection);272273 Ok(())274 }275276 #[weight = 0]277 pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {278279 let sender = ensure_signed(origin)?;280 Self::check_owner_or_admin_permissions(collection_id, sender)?;281 let mut admin_arr: Vec<T::AccountId> = Vec::new();282283 if <AdminList<T>>::contains_key(collection_id)284 {285 admin_arr = <AdminList<T>>::get(collection_id);286 ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");287 }288289 admin_arr.push(new_admin_id);290 <AdminList<T>>::insert(collection_id, admin_arr);291292 Ok(())293 }294295 #[weight = 0]296 pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {297298 let sender = ensure_signed(origin)?;299 Self::check_owner_or_admin_permissions(collection_id, sender)?;300301 if <AdminList<T>>::contains_key(collection_id)302 {303 let mut admin_arr = <AdminList<T>>::get(collection_id);304 admin_arr.retain(|i| *i != account_id);305 <AdminList<T>>::insert(collection_id, admin_arr);306 }307308 Ok(())309 }310311 #[weight = 0]312 pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {313314 let sender = ensure_signed(origin)?;315 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");316317 let mut target_collection = <Collection<T>>::get(collection_id);318 ensure!(sender == target_collection.owner, "You do not own this collection");319320 target_collection.unconfirmed_sponsor = new_sponsor;321 <Collection<T>>::insert(collection_id, target_collection);322323 Ok(())324 }325326 #[weight = 0]327 pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {328329 let sender = ensure_signed(origin)?;330 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");331332 let mut target_collection = <Collection<T>>::get(collection_id);333 ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");334335 target_collection.sponsor = target_collection.unconfirmed_sponsor;336 target_collection.unconfirmed_sponsor = T::AccountId::default();337 <Collection<T>>::insert(collection_id, target_collection);338339 Ok(())340 }341342 #[weight = 0]343 pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {344345 let sender = ensure_signed(origin)?;346 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");347348 let mut target_collection = <Collection<T>>::get(collection_id);349 ensure!(sender == target_collection.owner, "You do not own this collection");350351 target_collection.sponsor = T::AccountId::default();352 <Collection<T>>::insert(collection_id, target_collection);353354 Ok(())355 }356 357 #[weight = 0]358 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {359360 let sender = ensure_signed(origin)?;361362 // check size363 let target_collection = <Collection<T>>::get(collection_id);364 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");365366 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;367368 let new_balance = <Balance<T>>::get(collection_id, owner.clone()).checked_add(1).unwrap();369 <Balance<T>>::insert(collection_id, owner.clone(), new_balance);370371 // TODO: implement other modes372 match target_collection.mode 373 {374 CollectionMode::NFT(_) => {375 // Create nft item376 let item = NftItemType {377 collection: collection_id,378 owner: owner,379 data: properties,380 };381 382 Self::add_nft_item(item)?;383 384 },385 CollectionMode::ReFungible(_, _) => {386 let mut owner_list = Vec::new();387 let value = (10 as u128).pow(target_collection.decimal_points);388 owner_list.push(Ownership {owner: owner, fraction: value});389390 let item = ReFungibleItemType {391 collection: collection_id,392 owner: owner_list,393 data: properties394 };395 396 Self::add_refungible_item(item)?;397 },398 _ => ()399 };400401 // call event402 Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));403404 Ok(())405 }406407 #[weight = 0]408 pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {409410 let sender = ensure_signed(origin)?;411 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);412 if !item_owner413 {414 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;415 }416 let target_collection = <Collection<T>>::get(collection_id);417418 match target_collection.mode 419 {420 CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,421 CollectionMode::ReFungible(_, _) => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,422 _ => ()423 };424425 // call event426 Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));427428 Ok(())429 }430431 #[weight = 0]432 pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {433434 let sender = ensure_signed(origin)?;435 ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");436437 let target_collection = <Collection<T>>::get(collection_id);438439 // TODO: implement other modes440 match target_collection.mode 441 {442 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,443 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,444 _ => ()445 };446447 Ok(())448 }449450 #[weight = 0]451 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {452453 let sender = ensure_signed(origin)?;454455 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);456 if !item_owner457 {458 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;459 }460461 let list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);462 if list_exists {463464 let mut list = <ApprovedList<T>>::get(collection_id, item_id);465 let item_contains = list.contains(&approved.clone());466467 if !item_contains {468 list.push(approved.clone());469 }470 } else {471472 let mut itm = Vec::new();473 itm.push(approved.clone());474 <ApprovedList<T>>::insert(collection_id, item_id, itm);475 }476477 Ok(())478 }479480 #[weight = 0]481 pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {482483 let mut approved: bool = false; 484 let sender = ensure_signed(origin)?;485 let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);486 if approved_list_exists487 {488 let list_itm = <ApprovedList<T>>::get(collection_id, item_id);489 approved = list_itm.contains(&recipient.clone());490 }491492 if !approved493 {494 Self::check_owner_or_admin_permissions(collection_id, sender)?;495 }496 497 let target_collection = <Collection<T>>::get(collection_id);498499 match target_collection.mode500 {501 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,502 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, from, recipient)?,503 // TODO: implement other modes504 _ => ()505 };506507 Ok(())508 }509510 #[weight = 0]511 pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {512513 // let no_perm_mes = "You do not have permissions to modify this collection";514 // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);515 // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));516 // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);517518 // // on_nft_received call519520 // Self::transfer(origin, collection_id, item_id, new_owner)?;521522 Ok(())523 }524525 #[weight = 0]526 pub fn set_offchain_schema(527 origin,528 collection_id: u64,529 schema: Vec<u8>530 ) -> DispatchResult {531 let sender = ensure_signed(origin)?;532 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;533 534 let mut target_collection = <Collection<T>>::get(collection_id);535 target_collection.offchain_schema = schema;536 <Collection<T>>::insert(collection_id, target_collection);537538 Ok(()) 539 }540541 // Shonsorship methods542 #[weight = 0]543 pub fn set_collection_sponsor(544 origin,545 collection_id: u64,546 address: T::AccountId547 ) -> DispatchResult {548 let sender = ensure_signed(origin)?;549 Self::check_owner_permissions(collection_id, sender)?;550 let mut collection = <Collection<T>>::get(collection_id);551 collection.unconfirmed_sponsor = address;552 <Collection<T>>::insert(collection_id, collection);553554 Ok(()) 555 }556557 #[weight = 0]558 pub fn confirm_sponsorship(559 origin,560 collection_id: u64,561 address: T::AccountId562 ) -> DispatchResult {563 let sender = ensure_signed(origin)?;564 let mut collection = <Collection<T>>::get(collection_id);565566 ensure!(collection.unconfirmed_sponsor == sender, "Only sponsor can confirm sponsorship");567568 collection.sponsor = collection.unconfirmed_sponsor;569 collection.unconfirmed_sponsor = T::AccountId::default();570 <Collection<T>>::insert(collection_id, collection);571572 Ok(()) 573 }574575 #[weight = 0]576 pub fn remove_collection_sponsor(577 origin,578 collection_id: u64579 ) -> DispatchResult {580 let sender = ensure_signed(origin)?;581 Self::check_owner_permissions(collection_id, sender)?;582 let mut collection = <Collection<T>>::get(collection_id);583 collection.unconfirmed_sponsor = T::AccountId::default();584 collection.sponsor = T::AccountId::default();585 <Collection<T>>::insert(collection_id, collection);586587 Ok(()) 588 }589590 }591}592593impl<T: Trait> Module<T> {594595 fn collection_exists(collection_id: u64) -> DispatchResult{596 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");597 Ok(())598 }599600 fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {601602 Self::collection_exists(collection_id)?;603604 let target_collection = <Collection<T>>::get(collection_id);605 ensure!(subject == target_collection.owner, "You do not own this collection");606607 Ok(())608 }609610 fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {611612 Self::collection_exists(collection_id)?;613614 let target_collection = <Collection<T>>::get(collection_id);615 let is_owner = subject == target_collection.owner;616617 let no_perm_mes = "You do not have permissions to modify this collection";618 let exists = <AdminList<T>>::contains_key(collection_id);619620 if !is_owner621 {622 ensure!(exists, no_perm_mes);623 ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);624 }625 Ok(())626 }627628 fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{629630 let target_collection = <Collection<T>>::get(collection_id);631632 match target_collection.mode {633 CollectionMode::NFT(_) => <NftItemList<T>>::get(collection_id, item_id).owner == subject,634 CollectionMode::Fungible(_) => <FungibleItemList<T>>::get(collection_id, item_id).owner == subject,635 CollectionMode::ReFungible(_, _) => <ReFungibleItemList<T>>::get(collection_id, item_id).owner.iter().any(|i| i.owner == subject),636 CollectionMode::Invalid => false637 }638 }639640 fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {641642 let current_index = <ItemListIndex>::get(item.collection)643 .checked_add(1)644 .expect("Item list index id error");645646 Self::add_token_index(item.collection, current_index, item.owner.first().unwrap().owner.clone())?;647648 <ItemListIndex>::insert(item.collection, current_index);649 <ReFungibleItemList<T>>::insert(item.collection, current_index, item); 650651 Ok(())652 }653654 fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {655 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)?;659660 // update balance661 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(item.fraction as u64).unwrap();662 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);663664 // TODO665 <ReFungibleItemList<T>>::remove(collection_id, item_id);666667 Ok(())668 }669670 fn transfer_refungible(collection_id: u64, item_id: u64, value: u64, owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {671672 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);673 let item = full_item.owner.iter().filter(|i| i.owner == owner).next().unwrap();674 let amount = item.fraction;675676 ensure!(amount < value.into(),"Item balance not enouth");677678 // update balance679 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(value).unwrap();680 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);681682 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();683 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);684685 let old_owner = item.owner.clone();686 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);687688 // transfer689 if amount == value.into() && !new_owner_has_account690 {691 // change owner692 // new owner do not have account693 let mut new_full_item = full_item.clone();694 new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().owner = new_owner.clone();695 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);696697 // update index collection698 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;699 }700 else701 {702 let mut new_full_item = full_item.clone();703 new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().fraction -= amount;704705 // separate amount706 if new_owner_has_account {707 // new owner has account708 new_full_item.owner.iter_mut().find(|i| i.owner == new_owner).unwrap().fraction += amount;709 }710 else711 {712 // new owner do not have account713 new_full_item.owner.push(Ownership { owner: new_owner.clone(), fraction: amount});714 Self::add_token_index(collection_id, item_id, new_owner.clone())?;715 }716717 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);718 }719720 Ok(())721 }722 723 fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {724725 let current_index = <ItemListIndex>::get(item.collection)726 .checked_add(1)727 .expect("Item list index id error");728729 Self::add_token_index(item.collection, current_index, item.owner.clone())?;730731 <ItemListIndex>::insert(item.collection, current_index);732 <NftItemList<T>>::insert(item.collection, current_index, item);733734 Ok(())735 }736737 fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {738 739 let item = <NftItemList<T>>::get(collection_id, item_id);740 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;741742 // update balance743 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();744 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);745 <NftItemList<T>>::remove(collection_id, item_id);746747 Ok(())748 }749750 fn transfer_nft(collection_id: u64, item_id: u64, sender: T::AccountId, new_owner: T::AccountId) -> DispatchResult {751752 let mut item = <NftItemList<T>>::get(collection_id, item_id);753754 ensure!(sender == item.owner,"sender parameter and item owner must be equal");755756 // update balance757 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();758 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);759760 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();761 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);762763 // change owner764 let old_owner = item.owner.clone();765 item.owner = new_owner.clone();766 <NftItemList<T>>::insert(collection_id, item_id, item);767768 // update index collection769 Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;770771 // reset approved list772 let itm: Vec<T::AccountId> = Vec::new();773 <ApprovedList<T>>::insert(collection_id, item_id, itm);774775 Ok(())776 }777778 fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {779 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());780 if list_exists {781 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());782 let item_contains = list.contains(&item_index.clone());783784 if !item_contains {785 list.push(item_index.clone());786 }787788 <AddressTokens<T>>::insert(collection_id, owner.clone(), list);789 } else {790 let mut itm = Vec::new();791 itm.push(item_index.clone());792 <AddressTokens<T>>::insert(collection_id, owner, itm);793 }794795 Ok(())796 }797798 fn remove_token_index(799 collection_id: u64,800 item_index: u64,801 owner: T::AccountId,802 ) -> DispatchResult {803 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());804 if list_exists {805 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());806 let item_contains = list.contains(&item_index.clone());807808 if item_contains {809 list.retain(|&item| item != item_index);810 <AddressTokens<T>>::insert(collection_id, owner, list);811 }812 }813814 Ok(())815 }816817 fn move_token_index(818 collection_id: u64,819 item_index: u64,820 old_owner: T::AccountId,821 new_owner: T::AccountId,822 ) -> DispatchResult {823 Self::remove_token_index(collection_id, item_index, old_owner)?;824 Self::add_token_index(collection_id, item_index, new_owner)?;825826 Ok(())827 }828}829830831////////////////////////////////////////////////////////////////////////////////////////////////////832// Economic models833834/// Fee multiplier.835pub type Multiplier = FixedU128;836837type BalanceOf<T> =838 <<T as transaction_payment::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;839type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<840 <T as system::Trait>::AccountId,>>::NegativeImbalance;841842843844/// Require the transactor pay for themselves and maybe include a tip to gain additional priority845/// in the queue.846#[derive(Encode, Decode, Clone, Eq, PartialEq)]847pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(#[codec(compact)] BalanceOf<T>);848849impl<T:Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug for ChargeTransactionPayment<T> {850 #[cfg(feature = "std")]851 fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {852 write!(f, "ChargeTransactionPayment<{:?}>", self.0)853 }854 #[cfg(not(feature = "std"))]855 fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {856 Ok(())857 }858}859860impl<T:Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T> where861 T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,862 BalanceOf<T>: Send + Sync + FixedPointOperand,863{864 /// utility constructor. Used only in client/factory code.865 pub fn from(fee: BalanceOf<T>) -> Self {866 Self(fee)867 }868869 pub fn traditional_fee(870 len: usize,871 info: &DispatchInfoOf<T::Call>,872 tip: BalanceOf<T>,873 ) -> BalanceOf<T> where874 T::Call: Dispatchable<Info=DispatchInfo>,875 {876 <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)877 }878879 fn withdraw_fee(880 &self,881 who: &T::AccountId,882 call: &T::Call,883 info: &DispatchInfoOf<T::Call>,884 len: usize,885 ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {886 let tip = self.0;887888 // Set fee based on call type. Creating collection costs 1 Unique.889 // All other transactions have traditional fees so far890 let fee = match call.is_sub_type() {891 Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),892 _ => Self::traditional_fee(len, info, tip)893894 // Flat fee model, use only for testing purposes895 // _ => <BalanceOf<T>>::from(100)896 };897898 // Determine who is paying transaction fee based on ecnomic model899 // Parse call to extract collection ID and access collection sponsor900 let sponsor: T::AccountId = match call.is_sub_type() {901 Some(Call::create_item(collection_id, _properties, _owner)) => {902 <Collection<T>>::get(collection_id).sponsor903 },904 Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {905 <Collection<T>>::get(collection_id).sponsor906 },907908 _ => T::AccountId::default()909 };910911 let mut who_pays_fee: T::AccountId = sponsor.clone();912 if sponsor == T::AccountId::default() {913 who_pays_fee = who.clone();914 }915916 // Only mess with balances if fee is not zero.917 if fee.is_zero() {918 return Ok((fee, None));919 }920921 match <T as transaction_payment::Trait>::Currency::withdraw(922 &who_pays_fee,923 fee,924 if tip.is_zero() {925 WithdrawReason::TransactionPayment.into()926 } else {927 WithdrawReason::TransactionPayment | WithdrawReason::Tip928 },929 ExistenceRequirement::KeepAlive,930 ) {931 Ok(imbalance) => Ok((fee, Some(imbalance))),932 Err(_) => Err(InvalidTransaction::Payment.into()),933 }934 }935}936937impl<T:Trait + transaction_payment::Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> where938 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,939 T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,940{941 const IDENTIFIER: &'static str = "ChargeTransactionPayment";942 type AccountId = T::AccountId;943 type Call = T::Call;944 type AdditionalSigned = ();945 type Pre = (BalanceOf<T>, Self::AccountId, Option<NegativeImbalanceOf<T>>, BalanceOf<T>);946 fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { Ok(()) }947948 fn validate(949 &self,950 who: &Self::AccountId,951 call: &Self::Call,952 info: &DispatchInfoOf<Self::Call>,953 len: usize,954 ) -> TransactionValidity {955 let (fee, _) = self.withdraw_fee(who, call, info, len)?;956957 let mut r = ValidTransaction::default();958 // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which959 // will be a bit more than setting the priority to tip. For now, this is enough.960 r.priority = fee.saturated_into::<TransactionPriority>();961 Ok(r)962 }963964 fn pre_dispatch(965 self,966 who: &Self::AccountId,967 call: &Self::Call,968 info: &DispatchInfoOf<Self::Call>,969 len: usize970 ) -> Result<Self::Pre, TransactionValidityError> {971 let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;972 Ok((self.0, who.clone(), imbalance, fee))973 }974975 fn post_dispatch(976 pre: Self::Pre,977 info: &DispatchInfoOf<Self::Call>,978 post_info: &PostDispatchInfoOf<Self::Call>,979 len: usize,980 _result: &DispatchResult,981 ) -> Result<(), TransactionValidityError> {982 let (tip, who, imbalance, fee) = pre;983 if let Some(payed) = imbalance {984 let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(985 len as u32,986 info,987 post_info,988 tip,989 );990 let refund = fee.saturating_sub(actual_fee);991 let actual_payment = match <T as transaction_payment::Trait>::Currency::deposit_into_existing(&who, refund) {992 Ok(refund_imbalance) => {993 // The refund cannot be larger than the up front payed max weight.994 // `PostDispatchInfo::calc_unspent` guards against such a case.995 match payed.offset(refund_imbalance) {996 Ok(actual_payment) => actual_payment,997 Err(_) => return Err(InvalidTransaction::Payment.into()),998 }999 }1000 // We do not recreate the account using the refund. The up front payment1001 // is gone in that case.1002 Err(_) => payed,1003 };1004 let imbalances = actual_payment.split(tip);1005 <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(Some(imbalances.0).into_iter()1006 .chain(Some(imbalances.1)));1007 }1008 Ok(())1009 }1010}