1#![cfg_attr(not(feature = "std"), no_std)]23use codec::{Decode, Encode};456789101112pub use frame_support::{13 decl_event, decl_module, decl_storage,14 construct_runtime, parameter_types,15 traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason, Imbalance},16 weights::{17 DispatchInfo, PostDispatchInfo, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},18 IdentityFee, Weight, WeightToFeePolynomial, GetDispatchInfo, Pays,19 },20 StorageValue,21 dispatch::DispatchResult, 22 IsSubType,23 ensure24};2526use frame_system::{self as system, ensure_signed};27use sp_runtime::sp_std::prelude::Vec;28use sp_std::prelude::*;29use sp_runtime::{30 FixedU128, FixedPointOperand, 31 transaction_validity::{32 TransactionPriority, ValidTransaction, InvalidTransaction, TransactionValidityError, TransactionValidity33 },34 traits::{35 Saturating, Dispatchable, DispatchInfoOf, PostDispatchInfoOf, SignedExtension, Zero, SaturatedConversion,36 },37};3839#[cfg(test)]40mod mock;4142#[cfg(test)]43mod tests;4445#[derive(Encode, Decode, Default, Clone, PartialEq)]46#[cfg_attr(feature = "std", derive(Debug))]47pub struct CollectionType<AccountId> {48 pub owner: AccountId,49 pub next_item_id: u64,50 pub name: Vec<u16>, 51 pub description: Vec<u16>, 52 pub token_prefix: Vec<u8>, 53 pub custom_data_size: u32,54 pub sponsor: AccountId, 55 pub unconfirmed_sponsor: AccountId, 56}5758#[derive(Encode, Decode, Default, Clone, PartialEq)]59#[cfg_attr(feature = "std", derive(Debug))]60pub struct CollectionAdminsType<AccountId> {61 pub admin: AccountId,62 pub collection_id: u64,63}6465#[derive(Encode, Decode, Default, Clone, PartialEq)]66#[cfg_attr(feature = "std", derive(Debug))]67pub struct NftItemType<AccountId> {68 pub collection: u64,69 pub owner: AccountId,70 pub data: Vec<u8>,71}727374pub trait Trait: system::Trait {75 7677 78 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;7980}818283decl_storage! {84 85 86 trait Store for Module<T: Trait> as Nft {8788 89 pub NextCollectionID get(fn next_collection_id): u64;90 pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;91 pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;9293 94 pub Balance get(fn balance_count): map hasher(blake2_128_concat) (u64, T::AccountId) => u64;95 pub ApprovedList get(fn approved): map hasher(blake2_128_concat) (u64, u64) => Vec<T::AccountId>;9697 pub ItemList get(fn item_id): map hasher(blake2_128_concat) (u64, u64) => NftItemType<T::AccountId>;98 pub ItemListIndex get(fn item_index): map hasher(blake2_128_concat) u64 => u64;99100 pub AddressTokens get(fn address_tokens): map hasher(blake2_128_concat) (u64, T::AccountId) => Vec<u64>;101 }102}103104105decl_event!(106 pub enum Event<T>107 where108 AccountId = <T as system::Trait>::AccountId,109 {110 Created(u64, AccountId),111 ItemCreated(u64),112 ItemDestroyed(u64, u64),113 }114);115116117decl_module! {118 119 pub struct Module<T: Trait> for enum Call where origin: T::Origin {120121 122 123 fn deposit_event() = default;124125 126 127 128 129 #[weight = 0]130 pub fn create_collection( origin,131 collection_name: Vec<u16>,132 collection_description: Vec<u16>,133 token_prefix: Vec<u8>,134 custom_data_sz: u32) -> DispatchResult {135136 137 let who = ensure_signed(origin)?;138139 140 let mut name = collection_name.to_vec();141 name.push(0);142 ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");143144 let mut description = collection_description.to_vec();145 description.push(0);146 ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");147148 let mut prefix = token_prefix.to_vec();149 prefix.push(0);150 ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");151152 153 let next_id = NextCollectionID::get()154 .checked_add(1)155 .expect("collection id error");156157 NextCollectionID::put(next_id);158159 160 let new_collection = CollectionType {161 owner: who.clone(),162 name: name,163 description: description,164 token_prefix: prefix,165 next_item_id: next_id,166 custom_data_size: custom_data_sz,167 sponsor: T::AccountId::default(),168 unconfirmed_sponsor: T::AccountId::default(),169 };170171 172 <Collection<T>>::insert(next_id, new_collection);173174 175 Self::deposit_event(RawEvent::Created(next_id, who.clone()));176177 Ok(())178 }179180 #[weight = 0]181 pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {182183 let sender = ensure_signed(origin)?;184 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");185186 let owner = <Collection<T>>::get(collection_id).owner;187 ensure!(sender == owner, "You do not own this collection");188 <Collection<T>>::remove(collection_id);189190 Ok(())191 }192193 #[weight = 0]194 pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {195196 let sender = ensure_signed(origin)?;197 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");198199 let mut target_collection = <Collection<T>>::get(collection_id);200 ensure!(sender == target_collection.owner, "You do not own this collection");201202 target_collection.owner = new_owner;203 <Collection<T>>::insert(collection_id, target_collection);204205 Ok(())206 }207208 #[weight = 0]209 pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {210211 let sender = ensure_signed(origin)?;212 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");213214 let target_collection = <Collection<T>>::get(collection_id);215 let is_owner = sender == target_collection.owner;216217 let no_perm_mes = "You do not have permissions to modify this collection";218 let exists = <AdminList<T>>::contains_key(collection_id);219220 if !is_owner221 {222 ensure!(exists, no_perm_mes);223 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);224 }225226 let mut admin_arr: Vec<T::AccountId> = Vec::new();227 if exists228 {229 admin_arr = <AdminList<T>>::get(collection_id);230 ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");231 }232233 admin_arr.push(new_admin_id);234 <AdminList<T>>::insert(collection_id, admin_arr);235236 Ok(())237 }238239 #[weight = 0]240 pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {241242 let sender = ensure_signed(origin)?;243 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");244245 let target_collection = <Collection<T>>::get(collection_id);246 let is_owner = sender == target_collection.owner;247248 let no_perm_mes = "You do not have permissions to modify this collection";249 let exists = <AdminList<T>>::contains_key(collection_id);250251 if !is_owner252 {253 ensure!(exists, no_perm_mes);254 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);255 }256257 if exists258 {259 let mut admin_arr = <AdminList<T>>::get(collection_id);260 admin_arr.retain(|i| *i != account_id);261 <AdminList<T>>::insert(collection_id, admin_arr);262 }263264 Ok(())265 }266267 #[weight = 0]268 pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {269270 let sender = ensure_signed(origin)?;271 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");272273 let mut target_collection = <Collection<T>>::get(collection_id);274 ensure!(sender == target_collection.owner, "You do not own this collection");275276 target_collection.unconfirmed_sponsor = new_sponsor;277 <Collection<T>>::insert(collection_id, target_collection);278279 Ok(())280 }281282 #[weight = 0]283 pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {284285 let sender = ensure_signed(origin)?;286 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");287288 let mut target_collection = <Collection<T>>::get(collection_id);289 ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");290291 target_collection.sponsor = target_collection.unconfirmed_sponsor;292 target_collection.unconfirmed_sponsor = T::AccountId::default();293 <Collection<T>>::insert(collection_id, target_collection);294295 Ok(())296 }297298 #[weight = 0]299 pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {300301 let sender = ensure_signed(origin)?;302 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");303304 let mut target_collection = <Collection<T>>::get(collection_id);305 ensure!(sender == target_collection.owner, "You do not own this collection");306307 target_collection.sponsor = T::AccountId::default();308 <Collection<T>>::insert(collection_id, target_collection);309310 Ok(())311 }312 313314315 #[weight = 0]316 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>) -> DispatchResult {317318 let sender = ensure_signed(origin)?;319 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");320321 let target_collection = <Collection<T>>::get(collection_id);322 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");323 let is_owner = sender == target_collection.owner;324325 let no_perm_mes = "You do not have permissions to modify this collection";326 let exists = <AdminList<T>>::contains_key(collection_id);327328 if !is_owner329 {330 ensure!(exists, no_perm_mes);331 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);332 }333334 let new_balance = <Balance<T>>::get((collection_id, sender.clone())) + 1;335 <Balance<T>>::insert((collection_id, sender.clone()), new_balance);336337 338 let new_item = NftItemType {339 collection: collection_id,340 owner: sender,341 data: properties,342 };343344345 let current_index = <ItemListIndex>::get(collection_id)346 .checked_add(1)347 .expect("Item list index id error");348349 Self::add_token_index(collection_id, current_index, new_item.owner.clone())?;350351 <ItemListIndex>::insert(collection_id, current_index);352 <ItemList<T>>::insert((collection_id, current_index), new_item);353354 355 Self::deposit_event(RawEvent::ItemCreated(collection_id));356357 Ok(())358 }359360 #[weight = 0]361 pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {362363 let sender = ensure_signed(origin)?;364 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");365366 let target_collection = <Collection<T>>::get(collection_id);367 let is_owner = sender == target_collection.owner;368369 ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");370 let item = <ItemList<T>>::get((collection_id, item_id));371372 if !is_owner373 {374 375 if item.owner != sender376 {377 let no_perm_mes = "You do not have permissions to modify this collection";378379 ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);380 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);381 }382 }383 <ItemList<T>>::remove((collection_id, item_id));384385 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;386387 388 let new_balance = <Balance<T>>::get((collection_id, item.owner.clone())) - 1;389 <Balance<T>>::insert((collection_id, item.owner.clone()), new_balance);390391 392 Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));393394 Ok(())395 }396397 #[weight = 0]398 pub fn transfer(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {399400 let sender = ensure_signed(origin)?;401 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");402403 let target_collection = <Collection<T>>::get(collection_id);404 let is_owner = sender == target_collection.owner;405406 ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");407 let mut item = <ItemList<T>>::get((collection_id, item_id));408409 if !is_owner410 {411 412 if item.owner != sender413 {414 let no_perm_mes = "You do not have permissions to modify this collection";415416 ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);417 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);418 }419 }420 <ItemList<T>>::remove((collection_id, item_id));421422 423 let balance_old_owner = <Balance<T>>::get((collection_id, item.owner.clone())) - 1;424 <Balance<T>>::insert((collection_id, item.owner.clone()), balance_old_owner);425426 let balance_new_owner = <Balance<T>>::get((collection_id, new_owner.clone())) + 1;427 <Balance<T>>::insert((collection_id, new_owner.clone()), balance_new_owner);428429 430 let old_owner = item.owner.clone();431 item.owner = new_owner.clone();432 <ItemList<T>>::insert((collection_id, item_id), item);433434 435 Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;436437 438 let itm: Vec<T::AccountId> = Vec::new();439 <ApprovedList<T>>::insert((collection_id, item_id), itm);440441 Ok(())442 }443444 #[weight = 0]445 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {446447 let sender = ensure_signed(origin)?;448 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");449450 let target_collection = <Collection<T>>::get(collection_id);451 let is_owner = sender == target_collection.owner;452453 ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");454 let item = <ItemList<T>>::get((collection_id, item_id));455456 if !is_owner457 {458 459 if item.owner != sender460 {461 let no_perm_mes = "You do not have permissions to modify this collection";462463 ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);464 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);465 }466 }467468 let list_exists = <ApprovedList<T>>::contains_key((collection_id, item_id));469 if list_exists {470471 let mut list = <ApprovedList<T>>::get((collection_id, item_id));472 let item_contains = list.contains(&approved.clone());473474 if !item_contains {475 list.push(approved.clone());476 }477 } else {478479 let mut itm = Vec::new();480 itm.push(approved.clone());481 <ApprovedList<T>>::insert((collection_id, item_id), itm);482 }483484 Ok(())485 }486487 #[weight = 0]488 pub fn transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {489490 let no_perm_mes = "You do not have permissions to modify this collection";491 ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);492 let list_itm = <ApprovedList<T>>::get((collection_id, item_id));493 ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);494495 Self::transfer(origin, collection_id, item_id, new_owner)?;496497 Ok(())498 }499500 #[weight = 0]501 pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {502503 let no_perm_mes = "You do not have permissions to modify this collection";504 ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);505 let list_itm = <ApprovedList<T>>::get((collection_id, item_id));506 ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);507508 509510 Self::transfer(origin, collection_id, item_id, new_owner)?;511512 Ok(())513 }514 }515}516517impl<T: Trait> Module<T> {518 fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {519 let list_exists = <AddressTokens<T>>::contains_key((collection_id, owner.clone()));520 if list_exists {521 let mut list = <AddressTokens<T>>::get((collection_id, owner.clone()));522 let item_contains = list.contains(&item_index.clone());523524 if !item_contains {525 list.push(item_index.clone());526 }527528 <AddressTokens<T>>::insert((collection_id, owner.clone()), list);529 } else {530 let mut itm = Vec::new();531 itm.push(item_index.clone());532 <AddressTokens<T>>::insert((collection_id, owner), itm);533 }534535 Ok(())536 }537538 fn remove_token_index(539 collection_id: u64,540 item_index: u64,541 owner: T::AccountId,542 ) -> DispatchResult {543 let list_exists = <AddressTokens<T>>::contains_key((collection_id, owner.clone()));544 if list_exists {545 let mut list = <AddressTokens<T>>::get((collection_id, owner.clone()));546 let item_contains = list.contains(&item_index.clone());547548 if item_contains {549 list.retain(|&item| item != item_index);550 <AddressTokens<T>>::insert((collection_id, owner), list);551 }552 }553554 Ok(())555 }556557 fn move_token_index(558 collection_id: u64,559 item_index: u64,560 old_owner: T::AccountId,561 new_owner: T::AccountId,562 ) -> DispatchResult {563 Self::remove_token_index(collection_id, item_index, old_owner)?;564 Self::add_token_index(collection_id, item_index, new_owner)?;565566 Ok(())567 }568}569570571572573574575pub type Multiplier = FixedU128;576577type BalanceOf<T> =578 <<T as transaction_payment::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;579type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<580 <T as system::Trait>::AccountId,>>::NegativeImbalance;581582583584585586#[derive(Encode, Decode, Clone, Eq, PartialEq)]587pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(#[codec(compact)] BalanceOf<T>);588589impl<T:Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug for ChargeTransactionPayment<T> {590 #[cfg(feature = "std")]591 fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {592 write!(f, "ChargeTransactionPayment<{:?}>", self.0)593 }594 #[cfg(not(feature = "std"))]595 fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {596 Ok(())597 }598}599600impl<T:Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T> where601 T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,602 BalanceOf<T>: Send + Sync + FixedPointOperand,603{604 605 pub fn from(fee: BalanceOf<T>) -> Self {606 Self(fee)607 }608609 pub fn traditional_fee(610 len: usize,611 info: &DispatchInfoOf<T::Call>,612 tip: BalanceOf<T>,613 ) -> BalanceOf<T> where614 T::Call: Dispatchable<Info=DispatchInfo>,615 {616 <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)617 }618619 fn withdraw_fee(620 &self,621 who: &T::AccountId,622 call: &T::Call,623 info: &DispatchInfoOf<T::Call>,624 len: usize,625 ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {626 let tip = self.0;627628 629 630 let fee = match call.is_sub_type() {631 Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),632 _ => Self::traditional_fee(len, info, tip)633634 635 636 };637638 639 640 let sponsor: T::AccountId = match call.is_sub_type() {641 Some(Call::create_item(collection_id, _properties)) => {642 <Collection<T>>::get(collection_id).sponsor643 },644 Some(Call::transfer(collection_id, _item_id, _new_owner)) => {645 <Collection<T>>::get(collection_id).sponsor646 },647648 _ => T::AccountId::default()649 };650651 let mut who_pays_fee: T::AccountId = sponsor.clone();652 if sponsor == T::AccountId::default() {653 who_pays_fee = who.clone();654 }655656 657 if fee.is_zero() {658 return Ok((fee, None));659 }660661 match <T as transaction_payment::Trait>::Currency::withdraw(662 &who_pays_fee,663 fee,664 if tip.is_zero() {665 WithdrawReason::TransactionPayment.into()666 } else {667 WithdrawReason::TransactionPayment | WithdrawReason::Tip668 },669 ExistenceRequirement::KeepAlive,670 ) {671 Ok(imbalance) => Ok((fee, Some(imbalance))),672 Err(_) => Err(InvalidTransaction::Payment.into()),673 }674 }675}676677impl<T:Trait + transaction_payment::Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> where678 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,679 T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,680{681 const IDENTIFIER: &'static str = "ChargeTransactionPayment";682 type AccountId = T::AccountId;683 type Call = T::Call;684 type AdditionalSigned = ();685 type Pre = (BalanceOf<T>, Self::AccountId, Option<NegativeImbalanceOf<T>>, BalanceOf<T>);686 fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { Ok(()) }687688 fn validate(689 &self,690 who: &Self::AccountId,691 call: &Self::Call,692 info: &DispatchInfoOf<Self::Call>,693 len: usize,694 ) -> TransactionValidity {695 let (fee, _) = self.withdraw_fee(who, call, info, len)?;696697 let mut r = ValidTransaction::default();698 699 700 r.priority = fee.saturated_into::<TransactionPriority>();701 Ok(r)702 }703704 fn pre_dispatch(705 self,706 who: &Self::AccountId,707 call: &Self::Call,708 info: &DispatchInfoOf<Self::Call>,709 len: usize710 ) -> Result<Self::Pre, TransactionValidityError> {711 let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;712 Ok((self.0, who.clone(), imbalance, fee))713 }714715 fn post_dispatch(716 pre: Self::Pre,717 info: &DispatchInfoOf<Self::Call>,718 post_info: &PostDispatchInfoOf<Self::Call>,719 len: usize,720 _result: &DispatchResult,721 ) -> Result<(), TransactionValidityError> {722 let (tip, who, imbalance, fee) = pre;723 if let Some(payed) = imbalance {724 let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(725 len as u32,726 info,727 post_info,728 tip,729 );730 let refund = fee.saturating_sub(actual_fee);731 let actual_payment = match <T as transaction_payment::Trait>::Currency::deposit_into_existing(&who, refund) {732 Ok(refund_imbalance) => {733 734 735 match payed.offset(refund_imbalance) {736 Ok(actual_payment) => actual_payment,737 Err(_) => return Err(InvalidTransaction::Payment.into()),738 }739 }740 741 742 Err(_) => payed,743 };744 let imbalances = actual_payment.split(tip);745 <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(Some(imbalances.0).into_iter()746 .chain(Some(imbalances.1)));747 }748 Ok(())749 }750}