difftreelog
Merge pull request #6 from usetech-llc/feature/white_list_nft_62-64
in: master
Feature/white list nft 62 64
4 files changed
README.mddiffbeforeafterboth--- a/README.md
+++ b/README.md
@@ -142,6 +142,12 @@
"enable_println": "bool",
"max_subject_len": "u32"
},
+ "AccessMode": {
+ "_enum": [
+ "Normal",
+ "WhiteList"
+ ]
+ },
"CollectionMode": {
"_enum": {
"Invalid": null,
@@ -181,12 +187,13 @@
"CollectionType": {
"Owner": "AccountId",
"Mode": "CollectionMode",
- "Access": "u8",
+ "Access": "AccessMode",
"DecimalPoints": "u32",
"Name": "Vec<u16>",
"Description": "Vec<u16>",
"TokenPrefix": "Vec<u8>",
"CustomDataSize": "u32",
+ "MintMode": "bool",
"OffchainSchema": "Vec<u8>",
"Sponsor": "AccountId",
"UnconfirmedSponsor": "AccountId"
@@ -196,4 +203,5 @@
"LookupSource": "AccountId",
"Weight": "u64"
}
+
```
\ No newline at end of file
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.rs5use codec::{Decode, Encode};6pub use frame_support::{7 construct_runtime, decl_event, decl_module, decl_storage,8 dispatch::DispatchResult,9 ensure, parameter_types,10 traits::{11 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,12 Randomness, WithdrawReason,13 },14 weights::{15 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},16 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,17 WeightToFeePolynomial,18 },19 IsSubType, StorageValue,20};2122use frame_system::{self as system, ensure_signed};23use sp_runtime::sp_std::prelude::Vec;24use sp_runtime::{25 traits::{26 DispatchInfoOf, Dispatchable, PostDispatchInfoOf, SaturatedConversion, Saturating,27 SignedExtension, Zero,28 },29 transaction_validity::{30 InvalidTransaction, TransactionPriority, TransactionValidity, TransactionValidityError,31 ValidTransaction,32 },33 FixedPointOperand, FixedU128,34};35use sp_std::prelude::*;3637#[cfg(test)]38mod mock;3940#[cfg(test)]41mod tests;4243#[derive(Encode, Decode, Debug, Eq, Clone, PartialEq)]44pub enum CollectionMode {45 Invalid,46 // custom data size47 NFT(u32),48 // decimal points49 Fungible(u32),50 // custom data size and decimal points51 ReFungible(u32, u32),52}5354impl Into<u8> for CollectionMode {55 fn into(self) -> u8 {56 match self {57 CollectionMode::Invalid => 0,58 CollectionMode::NFT(_) => 1,59 CollectionMode::Fungible(_) => 2,60 CollectionMode::ReFungible(_, _) => 3,61 }62 }63}6465#[derive(Encode, Decode, Debug, Clone, PartialEq)]66pub enum AccessMode {67 Normal,68 WhiteList,69}70impl Default for AccessMode {71 fn default() -> Self {72 Self::Normal73 }74}7576impl Default for CollectionMode {77 fn default() -> Self {78 Self::Invalid79 }80}8182#[derive(Encode, Decode, Default, Clone, PartialEq)]83#[cfg_attr(feature = "std", derive(Debug))]84pub struct Ownership<AccountId> {85 pub owner: AccountId,86 pub fraction: u128,87}8889#[derive(Encode, Decode, Default, Clone, PartialEq)]90#[cfg_attr(feature = "std", derive(Debug))]91pub struct CollectionType<AccountId> {92 pub owner: AccountId,93 pub mode: CollectionMode,94 pub access: AccessMode,95 pub decimal_points: u32,96 pub name: Vec<u16>, // 64 include null escape char97 pub description: Vec<u16>, // 256 include null escape char98 pub token_prefix: Vec<u8>, // 16 include null escape char99 pub custom_data_size: u32,100 pub offchain_schema: Vec<u8>,101 pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender102 pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship103}104105#[derive(Encode, Decode, Default, Clone, PartialEq)]106#[cfg_attr(feature = "std", derive(Debug))]107pub struct CollectionAdminsType<AccountId> {108 pub admin: AccountId,109 pub collection_id: u64,110}111112#[derive(Encode, Decode, Default, Clone, PartialEq)]113#[cfg_attr(feature = "std", derive(Debug))]114pub struct NftItemType<AccountId> {115 pub collection: u64,116 pub owner: AccountId,117 pub data: Vec<u8>,118}119120#[derive(Encode, Decode, Default, Clone, PartialEq)]121#[cfg_attr(feature = "std", derive(Debug))]122pub struct FungibleItemType<AccountId> {123 pub collection: u64,124 pub owner: AccountId,125 pub value: u128,126}127128#[derive(Encode, Decode, Default, Clone, PartialEq)]129#[cfg_attr(feature = "std", derive(Debug))]130pub struct ReFungibleItemType<AccountId> {131 pub collection: u64,132 pub owner: Vec<Ownership<AccountId>>,133 pub data: Vec<u8>,134}135136#[derive(Encode, Decode, Default, Clone, PartialEq)]137#[cfg_attr(feature = "std", derive(Debug))]138pub struct ApprovePermissions<AccountId> {139 pub approved: AccountId,140 pub amount: u64,141}142143#[derive(Encode, Decode, Default, Clone, PartialEq)]144#[cfg_attr(feature = "std", derive(Debug))]145pub struct VestingItem<AccountId, Moment> {146 pub sender: AccountId,147 pub recipient: AccountId,148 pub collection_id: u64,149 pub item_id: u64,150 pub amount: u64,151 pub vesting_date: Moment,152}153154pub trait Trait: system::Trait {155 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;156}157158decl_storage! {159 trait Store for Module<T: Trait> as Nft {160161 // Private members162 NextCollectionID: u64;163 CreatedCollectionCount: u64;164 ChainVersion: u64;165 ItemListIndex: map hasher(blake2_128_concat) u64 => u64;166167 pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;168 pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;169 pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;170171 /// Balance owner per collection map172 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;173174 /// second parameter: item id + owner account id175 pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) (u64, T::AccountId) => Vec<ApprovePermissions<T::AccountId>>;176177 /// Item collections178 pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;179 pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;180 pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;181182 // Active vesting list183 // pub VestingList get(fn vesting): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => VestingItem<T::AccountId, T::Moment>;184185 /// Index list186 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;187188 // Sponsorship189 pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;190 pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;191 }192}193194decl_event!(195 pub enum Event<T>196 where197 AccountId = <T as system::Trait>::AccountId,198 {199 Created(u64, u8, AccountId),200 ItemCreated(u64, u64),201 ItemDestroyed(u64, u64),202 }203);204205decl_module! {206 pub struct Module<T: Trait> for enum Call where origin: T::Origin {207208 fn deposit_event() = default;209210 fn on_initialize(now: T::BlockNumber) -> Weight {211212 if ChainVersion::get() == 0213 {214 let value = NextCollectionID::get();215 CreatedCollectionCount::put(value);216 ChainVersion::put(2);217 }218219 0220 }221222 // Create collection of NFT with given parameters223 //224 // @param customDataSz size of custom data in each collection item225 // returns collection ID226 #[weight = 0]227 pub fn create_collection( origin,228 collection_name: Vec<u16>,229 collection_description: Vec<u16>,230 token_prefix: Vec<u8>,231 mode: CollectionMode) -> DispatchResult {232233 // Anyone can create a collection234 let who = ensure_signed(origin)?;235 let custom_data_size = match mode {236 CollectionMode::NFT(size) => size,237 CollectionMode::ReFungible(size, _) => size,238 _ => 0239 };240241 let decimal_points = match mode {242 CollectionMode::Fungible(points) => points,243 CollectionMode::ReFungible(_, points) => points,244 _ => 0245 };246247 // check params248 ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4");249250 let mut name = collection_name.to_vec();251 name.push(0);252 ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");253254 let mut description = collection_description.to_vec();255 description.push(0);256 ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");257258 let mut prefix = token_prefix.to_vec();259 prefix.push(0);260 ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");261262 // Generate next collection ID263 let next_id = CreatedCollectionCount::get()264 .checked_add(1)265 .expect("collection id error");266267 CreatedCollectionCount::put(next_id);268269 // Create new collection270 let new_collection = CollectionType {271 owner: who.clone(),272 name: name,273 mode: mode.clone(),274 access: AccessMode::Normal,275 description: description,276 decimal_points: decimal_points,277 token_prefix: prefix,278 offchain_schema: Vec::new(),279 custom_data_size: custom_data_size,280 sponsor: T::AccountId::default(),281 unconfirmed_sponsor: T::AccountId::default(),282 };283284 // Add new collection to map285 <Collection<T>>::insert(next_id, new_collection);286287 // call event288 Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));289290 Ok(())291 }292293 #[weight = 0]294 pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {295296 let sender = ensure_signed(origin)?;297 Self::check_owner_permissions(collection_id, sender)?;298299 // TODO Items remove300 <AddressTokens<T>>::remove_prefix(collection_id);301 <ApprovedList<T>>::remove_prefix(collection_id);302 <Balance<T>>::remove_prefix(collection_id);303 <ItemListIndex>::remove(collection_id);304 <AdminList<T>>::remove(collection_id);305 <Collection<T>>::remove(collection_id);306 <WhiteList<T>>::remove(collection_id);307308 Ok(())309 }310311 #[weight = 0]312 pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {313314 let sender = ensure_signed(origin)?;315 Self::check_owner_permissions(collection_id, sender)?;316 let mut target_collection = <Collection<T>>::get(collection_id);317 target_collection.owner = new_owner;318 <Collection<T>>::insert(collection_id, target_collection);319320 Ok(())321 }322323 #[weight = 0]324 pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {325326 let sender = ensure_signed(origin)?;327 Self::check_owner_or_admin_permissions(collection_id, sender)?;328 let mut admin_arr: Vec<T::AccountId> = Vec::new();329330 if <AdminList<T>>::contains_key(collection_id)331 {332 admin_arr = <AdminList<T>>::get(collection_id);333 ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");334 }335336 admin_arr.push(new_admin_id);337 <AdminList<T>>::insert(collection_id, admin_arr);338339 Ok(())340 }341342 #[weight = 0]343 pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {344345 let sender = ensure_signed(origin)?;346 Self::check_owner_or_admin_permissions(collection_id, sender)?;347348 if <AdminList<T>>::contains_key(collection_id)349 {350 let mut admin_arr = <AdminList<T>>::get(collection_id);351 admin_arr.retain(|i| *i != account_id);352 <AdminList<T>>::insert(collection_id, admin_arr);353 }354355 Ok(())356 }357358 #[weight = 0]359 pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {360361 let sender = ensure_signed(origin)?;362 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");363364 let mut target_collection = <Collection<T>>::get(collection_id);365 ensure!(sender == target_collection.owner, "You do not own this collection");366367 target_collection.unconfirmed_sponsor = new_sponsor;368 <Collection<T>>::insert(collection_id, target_collection);369370 Ok(())371 }372373 #[weight = 0]374 pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {375376 let sender = ensure_signed(origin)?;377 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");378379 let mut target_collection = <Collection<T>>::get(collection_id);380 ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");381382 target_collection.sponsor = target_collection.unconfirmed_sponsor;383 target_collection.unconfirmed_sponsor = T::AccountId::default();384 <Collection<T>>::insert(collection_id, target_collection);385386 Ok(())387 }388389 #[weight = 0]390 pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {391392 let sender = ensure_signed(origin)?;393 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");394395 let mut target_collection = <Collection<T>>::get(collection_id);396 ensure!(sender == target_collection.owner, "You do not own this collection");397398 target_collection.sponsor = T::AccountId::default();399 <Collection<T>>::insert(collection_id, target_collection);400401 Ok(())402 }403404 #[weight = 0]405 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {406407 let sender = ensure_signed(origin)?;408 let target_collection = <Collection<T>>::get(collection_id);409 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;410411 match target_collection.mode412 {413 CollectionMode::NFT(_) => {414415 // check size416 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");417418 // Create nft item419 let item = NftItemType {420 collection: collection_id,421 owner: owner,422 data: properties.clone(),423 };424425 Self::add_nft_item(item)?;426427 },428 CollectionMode::Fungible(_) => {429430 // check size431 ensure!(properties.len() as u32 == 0, "Size of item must be 0 with fungible type");432433 let item = FungibleItemType {434 collection: collection_id,435 owner: owner,436 value: (10 as u128).pow(target_collection.decimal_points)437 };438439 Self::add_fungible_item(item)?;440 },441 CollectionMode::ReFungible(_, _) => {442443 // check size444 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");445446 let mut owner_list = Vec::new();447 let value = (10 as u128).pow(target_collection.decimal_points);448 owner_list.push(Ownership {owner: owner.clone(), fraction: value});449450 let item = ReFungibleItemType {451 collection: collection_id,452 owner: owner_list,453 data: properties.clone()454 };455456 Self::add_refungible_item(item)?;457 },458 _ => { ensure!(1 == 0,"just error"); }459460 };461462 // call event463 Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));464465 Ok(())466 }467468 #[weight = 0]469 pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {470471 let sender = ensure_signed(origin)?;472 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);473 if !item_owner474 {475 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;476 }477 let target_collection = <Collection<T>>::get(collection_id);478479 match target_collection.mode480 {481 CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,482 CollectionMode::Fungible(_) => Self::burn_fungible_item(collection_id, item_id)?,483 CollectionMode::ReFungible(_, _) => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,484 _ => ()485 };486487 // call event488 Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));489490 Ok(())491 }492493 #[weight = 0]494 pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {495496 let sender = ensure_signed(origin)?;497 ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");498499 let target_collection = <Collection<T>>::get(collection_id);500501 // TODO: implement other modes502 match target_collection.mode503 {504 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,505 CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,506 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,507 _ => ()508 };509510 Ok(())511 }512513 #[weight = 0]514 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {515516 let sender = ensure_signed(origin)?;517518 // amount param stub519 let amount = 100000000;520521 ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id), "Only item owner can call transfer method");522523 let list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, sender.clone()));524 if list_exists {525526 let mut list = <ApprovedList<T>>::get(collection_id, (item_id, sender.clone()));527 let item_contains = list.iter().any(|i| i.approved == approved);528529 if !item_contains {530 list.push(ApprovePermissions { approved: approved.clone(), amount: amount });531 <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);532 }533 } else {534535 let mut list = Vec::new();536 list.push(ApprovePermissions { approved: approved.clone(), amount: amount });537 <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);538 }539540 Ok(())541 }542543 #[weight = 0]544 pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {545546 let sender = ensure_signed(origin)?;547 let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, from.clone()));548 if approved_list_exists549 {550 let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));551 let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());552 ensure!(opt_item.is_some(), "No approve found");553 ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved");554555 // remove approve556 let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))557 .into_iter().filter(|i| i.approved != sender.clone()).collect();558 <ApprovedList<T>>::insert(collection_id, (item_id, from.clone()), approve_list);559 }560 else561 {562 Self::check_owner_or_admin_permissions(collection_id, sender)?;563 }564565 let target_collection = <Collection<T>>::get(collection_id);566567 match target_collection.mode568 {569 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,570 CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, item_id, value, from.clone(), recipient)?,571 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,572 _ => ()573 };574575 Ok(())576 }577578 #[weight = 0]579 pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {580581 // let no_perm_mes = "You do not have permissions to modify this collection";582 // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);583 // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));584 // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);585586 // // on_nft_received call587588 // Self::transfer(origin, collection_id, item_id, new_owner)?;589590 Ok(())591 }592593 #[weight = 0]594 pub fn set_offchain_schema(595 origin,596 collection_id: u64,597 schema: Vec<u8>598 ) -> DispatchResult {599 let sender = ensure_signed(origin)?;600 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;601602 let mut target_collection = <Collection<T>>::get(collection_id);603 target_collection.offchain_schema = schema;604 <Collection<T>>::insert(collection_id, target_collection);605606 Ok(())607 }608 }609}610611impl<T: Trait> Module<T> {612 fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {613 let current_index = <ItemListIndex>::get(item.collection)614 .checked_add(1)615 .expect("Item list index id error");616 let itemcopy = item.clone();617 let owner = item.owner.clone();618 let value = item.value as u64;619620 Self::add_token_index(item.collection, current_index, owner.clone())?;621622 <ItemListIndex>::insert(item.collection, current_index);623 <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);624625 // Update balance626 let new_balance = <Balance<T>>::get(item.collection, owner.clone())627 .checked_add(value)628 .unwrap();629 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);630631 Ok(())632 }633634 fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {635 let current_index = <ItemListIndex>::get(item.collection)636 .checked_add(1)637 .expect("Item list index id error");638 let itemcopy = item.clone();639640 let value = item.owner.first().unwrap().fraction as u64;641 let owner = item.owner.first().unwrap().owner.clone();642643 Self::add_token_index(item.collection, current_index, owner.clone())?;644645 <ItemListIndex>::insert(item.collection, current_index);646 <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);647648 // Update balance649 let new_balance = <Balance<T>>::get(item.collection, owner.clone())650 .checked_add(value)651 .unwrap();652 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);653654 Ok(())655 }656657 fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {658 let current_index = <ItemListIndex>::get(item.collection)659 .checked_add(1)660 .expect("Item list index id error");661662 let item_owner = item.owner.clone();663 let collection_id = item.collection.clone();664 Self::add_token_index(collection_id, current_index, item.owner.clone())?;665666 <ItemListIndex>::insert(collection_id, current_index);667 <NftItemList<T>>::insert(collection_id, current_index, item);668669 // Update balance670 let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())671 .checked_add(1)672 .unwrap();673 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);674675 Ok(())676 }677678 fn burn_refungible_item(679 collection_id: u64,680 item_id: u64,681 owner: T::AccountId,682 ) -> DispatchResult {683 ensure!(684 <ReFungibleItemList<T>>::contains_key(collection_id, item_id),685 "Item does not exists"686 );687 let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);688 let item = collection689 .owner690 .iter()691 .filter(|&i| i.owner == owner)692 .next()693 .unwrap();694 Self::remove_token_index(collection_id, item_id, owner.clone())?;695696 // remove approve list697 <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));698699 // update balance700 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())701 .checked_sub(item.fraction as u64)702 .unwrap();703 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);704705 <ReFungibleItemList<T>>::remove(collection_id, item_id);706707 Ok(())708 }709710 fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {711 ensure!(712 <NftItemList<T>>::contains_key(collection_id, item_id),713 "Item does not exists"714 );715 let item = <NftItemList<T>>::get(collection_id, item_id);716 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;717718 // remove approve list719 <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));720721 // update balance722 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())723 .checked_sub(1)724 .unwrap();725 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);726 <NftItemList<T>>::remove(collection_id, item_id);727728 Ok(())729 }730731 fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {732 ensure!(733 <FungibleItemList<T>>::contains_key(collection_id, item_id),734 "Item does not exists"735 );736 let item = <FungibleItemList<T>>::get(collection_id, item_id);737 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;738739 // remove approve list740 <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));741742 // update balance743 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())744 .checked_sub(item.value as u64)745 .unwrap();746 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);747748 <FungibleItemList<T>>::remove(collection_id, item_id);749750 Ok(())751 }752753 fn collection_exists(collection_id: u64) -> DispatchResult {754 ensure!(755 <Collection<T>>::contains_key(collection_id),756 "This collection does not exist"757 );758 Ok(())759 }760761 fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {762 Self::collection_exists(collection_id)?;763764 let target_collection = <Collection<T>>::get(collection_id);765 ensure!(766 subject == target_collection.owner,767 "You do not own this collection"768 );769770 Ok(())771 }772773 fn check_owner_or_admin_permissions(774 collection_id: u64,775 subject: T::AccountId,776 ) -> DispatchResult {777 Self::collection_exists(collection_id)?;778779 let target_collection = <Collection<T>>::get(collection_id);780 let is_owner = subject == target_collection.owner;781782 let no_perm_mes = "You do not have permissions to modify this collection";783 let exists = <AdminList<T>>::contains_key(collection_id);784785 if !is_owner {786 ensure!(exists, no_perm_mes);787 ensure!(788 <AdminList<T>>::get(collection_id).contains(&subject),789 no_perm_mes790 );791 }792 Ok(())793 }794795 fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool {796 let target_collection = <Collection<T>>::get(collection_id);797798 match target_collection.mode {799 CollectionMode::NFT(_) => {800 <NftItemList<T>>::get(collection_id, item_id).owner == subject801 }802 CollectionMode::Fungible(_) => {803 <FungibleItemList<T>>::get(collection_id, item_id).owner == subject804 }805 CollectionMode::ReFungible(_, _) => {806 <ReFungibleItemList<T>>::get(collection_id, item_id)807 .owner808 .iter()809 .any(|i| i.owner == subject)810 }811 CollectionMode::Invalid => false,812 }813 }814815 fn transfer_fungible(816 collection_id: u64,817 item_id: u64,818 value: u64,819 owner: T::AccountId,820 new_owner: T::AccountId,821 ) -> DispatchResult {822 let full_item = <FungibleItemList<T>>::get(collection_id, item_id);823 let amount = full_item.value;824825 ensure!(amount >= value.into(), "Item balance not enouth");826827 // update balance828 let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone())829 .checked_sub(value)830 .unwrap();831 <Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);832833 let mut new_owner_account_id = 0;834 let new_owner_items = <AddressTokens<T>>::get(collection_id, new_owner.clone());835 if new_owner_items.len() > 0 {836 new_owner_account_id = new_owner_items[0];837 }838839 let val64 = value.into();840841 // transfer842 if amount == val64 && new_owner_account_id == 0 {843 // change owner844 // new owner do not have account845 let mut new_full_item = full_item.clone();846 new_full_item.owner = new_owner.clone();847 <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);848849 // update balance850 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())851 .checked_add(value)852 .unwrap();853 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);854855 // update index collection856 Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;857 } else {858 let mut new_full_item = full_item.clone();859 new_full_item.value -= val64;860861 // separate amount862 if new_owner_account_id > 0 {863 // new owner has account864 let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);865 item.value += val64;866867 // update balance868 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())869 .checked_add(value)870 .unwrap();871 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);872873 <FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);874 } else {875 // new owner do not have account876 let item = FungibleItemType {877 collection: collection_id,878 owner: new_owner.clone(),879 value: val64,880 };881882 Self::add_fungible_item(item)?;883 }884885 if amount == val64 {886 Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;887888 // remove approve list889 <ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));890 <FungibleItemList<T>>::remove(collection_id, item_id);891 }892893 <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);894 }895896 Ok(())897 }898899 fn transfer_refungible(900 collection_id: u64,901 item_id: u64,902 value: u64,903 owner: T::AccountId,904 new_owner: T::AccountId,905 ) -> DispatchResult {906 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);907 let item = full_item908 .owner909 .iter()910 .filter(|i| i.owner == owner)911 .next()912 .unwrap();913 let amount = item.fraction;914915 ensure!(amount >= value.into(), "Item balance not enouth");916917 // update balance918 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())919 .checked_sub(value)920 .unwrap();921 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);922923 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())924 .checked_add(value)925 .unwrap();926 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);927928 let old_owner = item.owner.clone();929 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);930 let val64 = value.into();931932 // transfer933 if amount == val64 && !new_owner_has_account {934 // change owner935 // new owner do not have account936 let mut new_full_item = full_item.clone();937 new_full_item938 .owner939 .iter_mut()940 .find(|i| i.owner == owner)941 .unwrap()942 .owner = new_owner.clone();943 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);944945 // update index collection946 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;947 } else {948 let mut new_full_item = full_item.clone();949 new_full_item950 .owner951 .iter_mut()952 .find(|i| i.owner == owner)953 .unwrap()954 .fraction -= val64;955956 // separate amount957 if new_owner_has_account {958 // new owner has account959 new_full_item960 .owner961 .iter_mut()962 .find(|i| i.owner == new_owner)963 .unwrap()964 .fraction += val64;965 } else {966 // new owner do not have account967 new_full_item.owner.push(Ownership {968 owner: new_owner.clone(),969 fraction: val64,970 });971 Self::add_token_index(collection_id, item_id, new_owner.clone())?;972 }973974 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);975 }976977 Ok(())978 }979980 fn transfer_nft(981 collection_id: u64,982 item_id: u64,983 sender: T::AccountId,984 new_owner: T::AccountId,985 ) -> DispatchResult {986 let mut item = <NftItemList<T>>::get(collection_id, item_id);987988 ensure!(989 sender == item.owner,990 "sender parameter and item owner must be equal"991 );992993 // update balance994 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())995 .checked_sub(1)996 .unwrap();997 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);998999 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1000 .checked_add(1)1001 .unwrap();1002 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);10031004 // change owner1005 let old_owner = item.owner.clone();1006 item.owner = new_owner.clone();1007 <NftItemList<T>>::insert(collection_id, item_id, item);10081009 // update index collection1010 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;10111012 // reset approved list1013 <ApprovedList<T>>::remove(collection_id, (item_id, old_owner));1014 Ok(())1015 }10161017 fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {1018 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1019 if list_exists {1020 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1021 let item_contains = list.contains(&item_index.clone());10221023 if !item_contains {1024 list.push(item_index.clone());1025 }10261027 <AddressTokens<T>>::insert(collection_id, owner.clone(), list);1028 } else {1029 let mut itm = Vec::new();1030 itm.push(item_index.clone());1031 <AddressTokens<T>>::insert(collection_id, owner, itm);1032 }10331034 Ok(())1035 }10361037 fn remove_token_index(1038 collection_id: u64,1039 item_index: u64,1040 owner: T::AccountId,1041 ) -> DispatchResult {1042 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1043 if list_exists {1044 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1045 let item_contains = list.contains(&item_index.clone());10461047 if item_contains {1048 list.retain(|&item| item != item_index);1049 <AddressTokens<T>>::insert(collection_id, owner, list);1050 }1051 }10521053 Ok(())1054 }10551056 fn move_token_index(1057 collection_id: u64,1058 item_index: u64,1059 old_owner: T::AccountId,1060 new_owner: T::AccountId,1061 ) -> DispatchResult {1062 Self::remove_token_index(collection_id, item_index, old_owner)?;1063 Self::add_token_index(collection_id, item_index, new_owner)?;10641065 Ok(())1066 }1067}10681069////////////////////////////////////////////////////////////////////////////////////////////////////1070// Economic models10711072/// Fee multiplier.1073pub type Multiplier = FixedU128;10741075type BalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1076 <T as system::Trait>::AccountId,1077>>::Balance;1078type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1079 <T as system::Trait>::AccountId,1080>>::NegativeImbalance;10811082/// Require the transactor pay for themselves and maybe include a tip to gain additional priority1083/// in the queue.1084#[derive(Encode, Decode, Clone, Eq, PartialEq)]1085pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(1086 #[codec(compact)] BalanceOf<T>,1087);10881089impl<T: Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug1090 for ChargeTransactionPayment<T>1091{1092 #[cfg(feature = "std")]1093 fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1094 write!(f, "ChargeTransactionPayment<{:?}>", self.0)1095 }1096 #[cfg(not(feature = "std"))]1097 fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1098 Ok(())1099 }1100}11011102impl<T: Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T>1103where1104 T::Call:1105 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1106 BalanceOf<T>: Send + Sync + FixedPointOperand,1107{1108 /// utility constructor. Used only in client/factory code.1109 pub fn from(fee: BalanceOf<T>) -> Self {1110 Self(fee)1111 }11121113 pub fn traditional_fee(1114 len: usize,1115 info: &DispatchInfoOf<T::Call>,1116 tip: BalanceOf<T>,1117 ) -> BalanceOf<T>1118 where1119 T::Call: Dispatchable<Info = DispatchInfo>,1120 {1121 <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)1122 }11231124 fn withdraw_fee(1125 &self,1126 who: &T::AccountId,1127 call: &T::Call,1128 info: &DispatchInfoOf<T::Call>,1129 len: usize,1130 ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {1131 let tip = self.0;11321133 // Set fee based on call type. Creating collection costs 1 Unique.1134 // All other transactions have traditional fees so far1135 let fee = match call.is_sub_type() {1136 Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1137 _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes1138 // _ => <BalanceOf<T>>::from(100)1139 };11401141 // Determine who is paying transaction fee based on ecnomic model1142 // Parse call to extract collection ID and access collection sponsor1143 let sponsor: T::AccountId = match call.is_sub_type() {1144 Some(Call::create_item(collection_id, _properties, _owner)) => {1145 <Collection<T>>::get(collection_id).sponsor1146 }1147 Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {1148 <Collection<T>>::get(collection_id).sponsor1149 }11501151 _ => T::AccountId::default(),1152 };11531154 let mut who_pays_fee: T::AccountId = sponsor.clone();1155 if sponsor == T::AccountId::default() {1156 who_pays_fee = who.clone();1157 }11581159 // Only mess with balances if fee is not zero.1160 if fee.is_zero() {1161 return Ok((fee, None));1162 }11631164 match <T as transaction_payment::Trait>::Currency::withdraw(1165 &who_pays_fee,1166 fee,1167 if tip.is_zero() {1168 WithdrawReason::TransactionPayment.into()1169 } else {1170 WithdrawReason::TransactionPayment | WithdrawReason::Tip1171 },1172 ExistenceRequirement::KeepAlive,1173 ) {1174 Ok(imbalance) => Ok((fee, Some(imbalance))),1175 Err(_) => Err(InvalidTransaction::Payment.into()),1176 }1177 }1178}11791180impl<T: Trait + transaction_payment::Trait + Send + Sync> SignedExtension1181 for ChargeTransactionPayment<T>1182where1183 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,1184 T::Call:1185 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1186{1187 const IDENTIFIER: &'static str = "ChargeTransactionPayment";1188 type AccountId = T::AccountId;1189 type Call = T::Call;1190 type AdditionalSigned = ();1191 type Pre = (1192 BalanceOf<T>,1193 Self::AccountId,1194 Option<NegativeImbalanceOf<T>>,1195 BalanceOf<T>,1196 );1197 fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {1198 Ok(())1199 }12001201 fn validate(1202 &self,1203 who: &Self::AccountId,1204 call: &Self::Call,1205 info: &DispatchInfoOf<Self::Call>,1206 len: usize,1207 ) -> TransactionValidity {1208 let (fee, _) = self.withdraw_fee(who, call, info, len)?;12091210 let mut r = ValidTransaction::default();1211 // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which1212 // will be a bit more than setting the priority to tip. For now, this is enough.1213 r.priority = fee.saturated_into::<TransactionPriority>();1214 Ok(r)1215 }12161217 fn pre_dispatch(1218 self,1219 who: &Self::AccountId,1220 call: &Self::Call,1221 info: &DispatchInfoOf<Self::Call>,1222 len: usize,1223 ) -> Result<Self::Pre, TransactionValidityError> {1224 let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;1225 Ok((self.0, who.clone(), imbalance, fee))1226 }12271228 fn post_dispatch(1229 pre: Self::Pre,1230 info: &DispatchInfoOf<Self::Call>,1231 post_info: &PostDispatchInfoOf<Self::Call>,1232 len: usize,1233 _result: &DispatchResult,1234 ) -> Result<(), TransactionValidityError> {1235 let (tip, who, imbalance, fee) = pre;1236 if let Some(payed) = imbalance {1237 let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(1238 len as u32, info, post_info, tip,1239 );1240 let refund = fee.saturating_sub(actual_fee);1241 let actual_payment =1242 match <T as transaction_payment::Trait>::Currency::deposit_into_existing(1243 &who, refund,1244 ) {1245 Ok(refund_imbalance) => {1246 // The refund cannot be larger than the up front payed max weight.1247 // `PostDispatchInfo::calc_unspent` guards against such a case.1248 match payed.offset(refund_imbalance) {1249 Ok(actual_payment) => actual_payment,1250 Err(_) => return Err(InvalidTransaction::Payment.into()),1251 }1252 }1253 // We do not recreate the account using the refund. The up front payment1254 // is gone in that case.1255 Err(_) => payed,1256 };1257 let imbalances = actual_payment.split(tip);1258 <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(1259 Some(imbalances.0).into_iter().chain(Some(imbalances.1)),1260 );1261 }1262 Ok(())1263 }1264}1#![cfg_attr(not(feature = "std"), no_std)]23/// For more guidance on Substrate FRAME, see the example pallet4/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs5use codec::{Decode, Encode};6pub use frame_support::{7 construct_runtime, decl_event, decl_module, decl_storage,8 dispatch::DispatchResult,9 ensure, parameter_types,10 traits::{11 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,12 Randomness, WithdrawReason,13 },14 weights::{15 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},16 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,17 WeightToFeePolynomial,18 },19 IsSubType, StorageValue,20};2122use frame_system::{self as system, ensure_signed};23use sp_runtime::sp_std::prelude::Vec;24use sp_runtime::{25 traits::{26 DispatchInfoOf, Dispatchable, PostDispatchInfoOf, SaturatedConversion, Saturating,27 SignedExtension, Zero,28 },29 transaction_validity::{30 InvalidTransaction, TransactionPriority, TransactionValidity, TransactionValidityError,31 ValidTransaction,32 },33 FixedPointOperand, FixedU128,34};35use sp_std::prelude::*;3637#[cfg(test)]38mod mock;3940#[cfg(test)]41mod tests;4243#[derive(Encode, Decode, Debug, Eq, Clone, PartialEq)]44pub enum CollectionMode {45 Invalid,46 // custom data size47 NFT(u32),48 // decimal points49 Fungible(u32),50 // custom data size and decimal points51 ReFungible(u32, u32),52}5354impl Into<u8> for CollectionMode {55 fn into(self) -> u8 {56 match self {57 CollectionMode::Invalid => 0,58 CollectionMode::NFT(_) => 1,59 CollectionMode::Fungible(_) => 2,60 CollectionMode::ReFungible(_, _) => 3,61 }62 }63}6465#[derive(Encode, Decode, Debug, Clone, PartialEq)]66pub enum AccessMode {67 Normal,68 WhiteList,69}70impl Default for AccessMode {71 fn default() -> Self {72 Self::Normal73 }74}7576impl Default for CollectionMode {77 fn default() -> Self {78 Self::Invalid79 }80}8182#[derive(Encode, Decode, Default, Clone, PartialEq)]83#[cfg_attr(feature = "std", derive(Debug))]84pub struct Ownership<AccountId> {85 pub owner: AccountId,86 pub fraction: u128,87}8889#[derive(Encode, Decode, Default, Clone, PartialEq)]90#[cfg_attr(feature = "std", derive(Debug))]91pub struct CollectionType<AccountId> {92 pub owner: AccountId,93 pub mode: CollectionMode,94 pub access: AccessMode,95 pub decimal_points: u32,96 pub name: Vec<u16>, // 64 include null escape char97 pub description: Vec<u16>, // 256 include null escape char98 pub token_prefix: Vec<u8>, // 16 include null escape char99 pub custom_data_size: u32,100 pub mint_mode: bool,101 pub offchain_schema: Vec<u8>,102 pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender103 pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship104}105106#[derive(Encode, Decode, Default, Clone, PartialEq)]107#[cfg_attr(feature = "std", derive(Debug))]108pub struct CollectionAdminsType<AccountId> {109 pub admin: AccountId,110 pub collection_id: u64,111}112113#[derive(Encode, Decode, Default, Clone, PartialEq)]114#[cfg_attr(feature = "std", derive(Debug))]115pub struct NftItemType<AccountId> {116 pub collection: u64,117 pub owner: AccountId,118 pub data: Vec<u8>,119}120121#[derive(Encode, Decode, Default, Clone, PartialEq)]122#[cfg_attr(feature = "std", derive(Debug))]123pub struct FungibleItemType<AccountId> {124 pub collection: u64,125 pub owner: AccountId,126 pub value: u128,127}128129#[derive(Encode, Decode, Default, Clone, PartialEq)]130#[cfg_attr(feature = "std", derive(Debug))]131pub struct ReFungibleItemType<AccountId> {132 pub collection: u64,133 pub owner: Vec<Ownership<AccountId>>,134 pub data: Vec<u8>,135}136137#[derive(Encode, Decode, Default, Clone, PartialEq)]138#[cfg_attr(feature = "std", derive(Debug))]139pub struct ApprovePermissions<AccountId> {140 pub approved: AccountId,141 pub amount: u64,142}143144#[derive(Encode, Decode, Default, Clone, PartialEq)]145#[cfg_attr(feature = "std", derive(Debug))]146pub struct VestingItem<AccountId, Moment> {147 pub sender: AccountId,148 pub recipient: AccountId,149 pub collection_id: u64,150 pub item_id: u64,151 pub amount: u64,152 pub vesting_date: Moment,153}154155pub trait Trait: system::Trait {156 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;157}158159decl_storage! {160 trait Store for Module<T: Trait> as Nft {161162 // Private members163 NextCollectionID: u64;164 CreatedCollectionCount: u64;165 ChainVersion: u64;166 ItemListIndex: map hasher(blake2_128_concat) u64 => u64;167168 pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;169 pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;170 pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;171172 /// Balance owner per collection map173 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;174175 /// second parameter: item id + owner account id176 pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) (u64, T::AccountId) => Vec<ApprovePermissions<T::AccountId>>;177178 /// Item collections179 pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;180 pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;181 pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;182183 /// Index list184 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;185186 // Sponsorship187 pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;188 pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;189 }190}191192decl_event!(193 pub enum Event<T>194 where195 AccountId = <T as system::Trait>::AccountId,196 {197 Created(u64, u8, AccountId),198 ItemCreated(u64, u64),199 ItemDestroyed(u64, u64),200 }201);202203decl_module! {204 pub struct Module<T: Trait> for enum Call where origin: T::Origin {205206 fn deposit_event() = default;207208 fn on_initialize(now: T::BlockNumber) -> Weight {209210 if ChainVersion::get() < 2211 {212 let value = NextCollectionID::get();213 CreatedCollectionCount::put(value);214 ChainVersion::put(2);215 }216217 0218 }219220 // Create collection of NFT with given parameters221 //222 // @param customDataSz size of custom data in each collection item223 // returns collection ID224 #[weight = 0]225 pub fn create_collection(origin,226 collection_name: Vec<u16>,227 collection_description: Vec<u16>,228 token_prefix: Vec<u8>,229 mode: CollectionMode) -> DispatchResult {230231 // Anyone can create a collection232 let who = ensure_signed(origin)?;233 let custom_data_size = match mode {234 CollectionMode::NFT(size) => size,235 CollectionMode::ReFungible(size, _) => size,236 _ => 0237 };238239 let decimal_points = match mode {240 CollectionMode::Fungible(points) => points,241 CollectionMode::ReFungible(_, points) => points,242 _ => 0243 };244245 // check params246 ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4");247248 let mut name = collection_name.to_vec();249 name.push(0);250 ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");251252 let mut description = collection_description.to_vec();253 description.push(0);254 ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");255256 let mut prefix = token_prefix.to_vec();257 prefix.push(0);258 ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");259260 // Generate next collection ID261 let next_id = CreatedCollectionCount::get()262 .checked_add(1)263 .expect("collection id error");264265 CreatedCollectionCount::put(next_id);266267 // Create new collection268 let new_collection = CollectionType {269 owner: who.clone(),270 name: name,271 mode: mode.clone(),272 mint_mode: false,273 access: AccessMode::Normal,274 description: description,275 decimal_points: decimal_points,276 token_prefix: prefix,277 offchain_schema: Vec::new(),278 custom_data_size: custom_data_size,279 sponsor: T::AccountId::default(),280 unconfirmed_sponsor: T::AccountId::default(),281 };282283 // Add new collection to map284 <Collection<T>>::insert(next_id, new_collection);285286 // call event287 Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));288289 Ok(())290 }291292 #[weight = 0]293 pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {294295 let sender = ensure_signed(origin)?;296 Self::check_owner_permissions(collection_id, sender)?;297298 // TODO Items remove299 <AddressTokens<T>>::remove_prefix(collection_id);300 <ApprovedList<T>>::remove_prefix(collection_id);301 <Balance<T>>::remove_prefix(collection_id);302 <ItemListIndex>::remove(collection_id);303 <AdminList<T>>::remove(collection_id);304 <Collection<T>>::remove(collection_id);305 <WhiteList<T>>::remove(collection_id);306307 Ok(())308 }309310 #[weight = 0]311 pub fn add_to_white_list(origin, collection_id: u64, address: T::AccountId) -> DispatchResult{312313 let sender = ensure_signed(origin)?;314 Self::check_owner_or_admin_permissions(collection_id, sender)?;315316 let mut white_list_collection: Vec<T::AccountId>;317 if <WhiteList<T>>::contains_key(collection_id) {318 white_list_collection = <WhiteList<T>>::get(collection_id);319 if !white_list_collection.contains(&address.clone())320 {321 white_list_collection.push(address.clone());322 }323 }324 else {325 white_list_collection = Vec::new();326 white_list_collection.push(address.clone());327 }328329 <WhiteList<T>>::insert(collection_id, white_list_collection);330 Ok(())331 }332333 #[weight = 0]334 pub fn remove_from_white_list(origin, collection_id: u64, address: T::AccountId) -> DispatchResult{335336 let sender = ensure_signed(origin)?;337 Self::check_owner_or_admin_permissions(collection_id, sender)?;338339 if <WhiteList<T>>::contains_key(collection_id) {340 let mut white_list_collection = <WhiteList<T>>::get(collection_id);341 if white_list_collection.contains(&address.clone())342 {343 white_list_collection.retain(|i| *i != address.clone());344 <WhiteList<T>>::insert(collection_id, white_list_collection);345 }346 }347348 Ok(())349 }350351 #[weight = 0]352 pub fn set_public_access_mode(origin, collection_id: u64, mode: AccessMode) -> DispatchResult353 {354 let sender = ensure_signed(origin)?;355356 Self::check_owner_permissions(collection_id, sender)?;357 let mut target_collection = <Collection<T>>::get(collection_id);358 target_collection.access = mode;359 <Collection<T>>::insert(collection_id, target_collection);360361 Ok(())362 }363364 #[weight = 0]365 pub fn set_mint_permission(origin, collection_id: u64, mint_permission: bool) -> DispatchResult366 {367 let sender = ensure_signed(origin)?;368369 Self::check_owner_permissions(collection_id, sender)?;370 let mut target_collection = <Collection<T>>::get(collection_id);371 target_collection.mint_mode = mint_permission;372 <Collection<T>>::insert(collection_id, target_collection);373374 Ok(())375 }376377 #[weight = 0]378 pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {379380 let sender = ensure_signed(origin)?;381 Self::check_owner_permissions(collection_id, sender)?;382 let mut target_collection = <Collection<T>>::get(collection_id);383 target_collection.owner = new_owner;384 <Collection<T>>::insert(collection_id, target_collection);385386 Ok(())387 }388389 #[weight = 0]390 pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {391392 let sender = ensure_signed(origin)?;393 Self::check_owner_or_admin_permissions(collection_id, sender)?;394 let mut admin_arr: Vec<T::AccountId> = Vec::new();395396 if <AdminList<T>>::contains_key(collection_id)397 {398 admin_arr = <AdminList<T>>::get(collection_id);399 ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");400 }401402 admin_arr.push(new_admin_id);403 <AdminList<T>>::insert(collection_id, admin_arr);404405 Ok(())406 }407408 #[weight = 0]409 pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {410411 let sender = ensure_signed(origin)?;412 Self::check_owner_or_admin_permissions(collection_id, sender)?;413414 if <AdminList<T>>::contains_key(collection_id)415 {416 let mut admin_arr = <AdminList<T>>::get(collection_id);417 admin_arr.retain(|i| *i != account_id);418 <AdminList<T>>::insert(collection_id, admin_arr);419 }420421 Ok(())422 }423424 #[weight = 0]425 pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {426427 let sender = ensure_signed(origin)?;428 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");429430 let mut target_collection = <Collection<T>>::get(collection_id);431 ensure!(sender == target_collection.owner, "You do not own this collection");432433 target_collection.unconfirmed_sponsor = new_sponsor;434 <Collection<T>>::insert(collection_id, target_collection);435436 Ok(())437 }438439 #[weight = 0]440 pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {441442 let sender = ensure_signed(origin)?;443 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");444445 let mut target_collection = <Collection<T>>::get(collection_id);446 ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");447448 target_collection.sponsor = target_collection.unconfirmed_sponsor;449 target_collection.unconfirmed_sponsor = T::AccountId::default();450 <Collection<T>>::insert(collection_id, target_collection);451452 Ok(())453 }454455 #[weight = 0]456 pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {457458 let sender = ensure_signed(origin)?;459 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");460461 let mut target_collection = <Collection<T>>::get(collection_id);462 ensure!(sender == target_collection.owner, "You do not own this collection");463464 target_collection.sponsor = T::AccountId::default();465 <Collection<T>>::insert(collection_id, target_collection);466467 Ok(())468 }469470 #[weight = 0]471 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {472473 let sender = ensure_signed(origin)?;474 Self::collection_exists(collection_id)?;475 let target_collection = <Collection<T>>::get(collection_id);476477 if !Self::is_owner_or_admin_permissions(collection_id, sender.clone()) {478 ensure!(target_collection.mint_mode == true, "Collection is not in mint mode");479 Self::check_white_list(collection_id, owner.clone())?;480 }481482 match target_collection.mode483 {484 CollectionMode::NFT(_) => {485486 // check size487 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");488489 // Create nft item490 let item = NftItemType {491 collection: collection_id,492 owner: owner,493 data: properties.clone(),494 };495496 Self::add_nft_item(item)?;497498 },499 CollectionMode::Fungible(_) => {500501 // check size502 ensure!(properties.len() as u32 == 0, "Size of item must be 0 with fungible type");503504 let item = FungibleItemType {505 collection: collection_id,506 owner: owner,507 value: (10 as u128).pow(target_collection.decimal_points)508 };509510 Self::add_fungible_item(item)?;511 },512 CollectionMode::ReFungible(_, _) => {513514 // check size515 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");516517 let mut owner_list = Vec::new();518 let value = (10 as u128).pow(target_collection.decimal_points);519 owner_list.push(Ownership {owner: owner.clone(), fraction: value});520521 let item = ReFungibleItemType {522 collection: collection_id,523 owner: owner_list,524 data: properties.clone()525 };526527 Self::add_refungible_item(item)?;528 },529 _ => { ensure!(1 == 0,"just error"); }530531 };532533 // call event534 Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));535536 Ok(())537 }538539 #[weight = 0]540 pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {541542 let sender = ensure_signed(origin)?;543 Self::collection_exists(collection_id)?;544 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);545 if !item_owner546 {547 if !Self::is_owner_or_admin_permissions(collection_id, sender.clone()) { 548 Self::check_white_list(collection_id, sender.clone())?;549 }550 }551 let target_collection = <Collection<T>>::get(collection_id);552553 match target_collection.mode554 {555 CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,556 CollectionMode::Fungible(_) => Self::burn_fungible_item(collection_id, item_id)?,557 CollectionMode::ReFungible(_, _) => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,558 _ => ()559 };560561 // call event562 Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));563564 Ok(())565 }566567 #[weight = 0]568 pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {569570 let sender = ensure_signed(origin)?;571 Self::check_white_list(collection_id, sender.clone())?;572 Self::check_white_list(collection_id, recipient.clone())?;573 let target_collection = <Collection<T>>::get(collection_id);574575 match target_collection.mode576 {577 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,578 CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,579 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,580 _ => ()581 };582583 Ok(())584 }585586 #[weight = 0]587 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {588589 let sender = ensure_signed(origin)?;590591 // amount param stub592 let amount = 100000000;593594 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);595 if !item_owner {596 Self::check_white_list(collection_id, approved.clone())?;597 }598599 let list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, sender.clone()));600 if list_exists {601602 let mut list = <ApprovedList<T>>::get(collection_id, (item_id, sender.clone()));603 let item_contains = list.iter().any(|i| i.approved == approved);604605 if !item_contains {606 list.push(ApprovePermissions { approved: approved.clone(), amount: amount });607 <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);608 }609 } else {610611 let mut list = Vec::new();612 list.push(ApprovePermissions { approved: approved.clone(), amount: amount });613 <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);614 }615616 Ok(())617 }618619 #[weight = 0]620 pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {621622 let sender = ensure_signed(origin)?;623 let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, from.clone()));624625 ensure!(approved_list_exists, "Only approved addresses can call this method");626627 Self::check_white_list(collection_id, from.clone())?;628 Self::check_white_list(collection_id, recipient.clone())?;629630 let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));631 let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());632 ensure!(opt_item.is_some(), "No approve found");633 ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved");634635 // remove approve636 let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))637 .into_iter().filter(|i| i.approved != sender.clone()).collect();638 <ApprovedList<T>>::insert(collection_id, (item_id, from.clone()), approve_list);639640 let target_collection = <Collection<T>>::get(collection_id);641642 match target_collection.mode643 {644 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,645 CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, item_id, value, from.clone(), recipient)?,646 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,647 _ => ()648 };649650 Ok(())651 }652653 #[weight = 0]654 pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {655656 // let no_perm_mes = "You do not have permissions to modify this collection";657 // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);658 // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));659 // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);660661 // // on_nft_received call662663 // Self::transfer(origin, collection_id, item_id, new_owner)?;664665 Ok(())666 }667668 #[weight = 0]669 pub fn set_offchain_schema(670 origin,671 collection_id: u64,672 schema: Vec<u8>673 ) -> DispatchResult {674 let sender = ensure_signed(origin)?;675 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;676677 let mut target_collection = <Collection<T>>::get(collection_id);678 target_collection.offchain_schema = schema;679 <Collection<T>>::insert(collection_id, target_collection);680681 Ok(())682 }683 }684}685686impl<T: Trait> Module<T> {687 fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {688 let current_index = <ItemListIndex>::get(item.collection)689 .checked_add(1)690 .expect("Item list index id error");691 let itemcopy = item.clone();692 let owner = item.owner.clone();693 let value = item.value as u64;694695 Self::add_token_index(item.collection, current_index, owner.clone())?;696697 <ItemListIndex>::insert(item.collection, current_index);698 <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);699700 // Update balance701 let new_balance = <Balance<T>>::get(item.collection, owner.clone())702 .checked_add(value)703 .unwrap();704 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);705706 Ok(())707 }708709 fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {710 let current_index = <ItemListIndex>::get(item.collection)711 .checked_add(1)712 .expect("Item list index id error");713 let itemcopy = item.clone();714715 let value = item.owner.first().unwrap().fraction as u64;716 let owner = item.owner.first().unwrap().owner.clone();717718 Self::add_token_index(item.collection, current_index, owner.clone())?;719720 <ItemListIndex>::insert(item.collection, current_index);721 <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);722723 // Update balance724 let new_balance = <Balance<T>>::get(item.collection, owner.clone())725 .checked_add(value)726 .unwrap();727 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);728729 Ok(())730 }731732 fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {733 let current_index = <ItemListIndex>::get(item.collection)734 .checked_add(1)735 .expect("Item list index id error");736737 let item_owner = item.owner.clone();738 let collection_id = item.collection.clone();739 Self::add_token_index(collection_id, current_index, item.owner.clone())?;740741 <ItemListIndex>::insert(collection_id, current_index);742 <NftItemList<T>>::insert(collection_id, current_index, item);743744 // Update balance745 let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())746 .checked_add(1)747 .unwrap();748 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);749750 Ok(())751 }752753 fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {754 ensure!(755 <ReFungibleItemList<T>>::contains_key(collection_id, item_id),756 "Item does not exists"757 );758 let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);759 let item = collection760 .owner761 .iter()762 .filter(|&i| i.owner == owner)763 .next()764 .unwrap();765 Self::remove_token_index(collection_id, item_id, owner.clone())?;766767 // remove approve list768 <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));769770 // update balance771 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())772 .checked_sub(item.fraction as u64)773 .unwrap();774 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);775776 <ReFungibleItemList<T>>::remove(collection_id, item_id);777778 Ok(())779 }780781 fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {782 ensure!(783 <NftItemList<T>>::contains_key(collection_id, item_id),784 "Item does not exists"785 );786 let item = <NftItemList<T>>::get(collection_id, item_id);787 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;788789 // remove approve list790 <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));791792 // update balance793 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())794 .checked_sub(1)795 .unwrap();796 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);797 <NftItemList<T>>::remove(collection_id, item_id);798799 Ok(())800 }801802 fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {803 ensure!(804 <FungibleItemList<T>>::contains_key(collection_id, item_id),805 "Item does not exists"806 );807 let item = <FungibleItemList<T>>::get(collection_id, item_id);808 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;809810 // remove approve list811 <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));812813 // update balance814 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())815 .checked_sub(item.value as u64)816 .unwrap();817 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);818819 <FungibleItemList<T>>::remove(collection_id, item_id);820821 Ok(())822 }823824 fn collection_exists(collection_id: u64) -> DispatchResult {825 ensure!(826 <Collection<T>>::contains_key(collection_id),827 "This collection does not exist"828 );829 Ok(())830 }831832 fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {833 Self::collection_exists(collection_id)?;834835 let target_collection = <Collection<T>>::get(collection_id);836 ensure!(837 subject == target_collection.owner,838 "You do not own this collection"839 );840841 Ok(())842 }843844 fn is_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> bool {845846 let target_collection = <Collection<T>>::get(collection_id);847 let mut result: bool = subject == target_collection.owner;848 let exists = <AdminList<T>>::contains_key(collection_id);849850 if !result & exists {851 if <AdminList<T>>::get(collection_id).contains(&subject) {852 result = true853 }854 }855856 result857 }858859 fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {860 861 Self::collection_exists(collection_id)?;862 let result = Self::is_owner_or_admin_permissions(collection_id, subject.clone());863864 ensure!(result, "You do not have permissions to modify this collection");865 Ok(())866 }867868 fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool {869 let target_collection = <Collection<T>>::get(collection_id);870871 match target_collection.mode {872 CollectionMode::NFT(_) => {873 <NftItemList<T>>::get(collection_id, item_id).owner == subject874 }875 CollectionMode::Fungible(_) => {876 <FungibleItemList<T>>::get(collection_id, item_id).owner == subject877 }878 CollectionMode::ReFungible(_, _) => {879 <ReFungibleItemList<T>>::get(collection_id, item_id)880 .owner881 .iter()882 .any(|i| i.owner == subject)883 }884 CollectionMode::Invalid => false,885 }886 }887888 fn check_white_list(collection_id: u64, address: T::AccountId) -> DispatchResult {889890 let mes = "Address is not in white list";891 ensure!(<WhiteList<T>>::contains_key(collection_id), mes);892 let wl = <WhiteList<T>>::get(collection_id);893 ensure!(wl.contains(&address.clone()), mes);894895 Ok(())896 }897898 fn transfer_fungible(899 collection_id: u64,900 item_id: u64,901 value: u64,902 owner: T::AccountId,903 new_owner: T::AccountId,904 ) -> DispatchResult {905906 ensure!(907 <FungibleItemList<T>>::contains_key(collection_id, item_id),908 "Item not exists"909 );910911 let full_item = <FungibleItemList<T>>::get(collection_id, item_id);912 let amount = full_item.value;913914 ensure!(amount >= value.into(), "Item balance not enouth");915916 // update balance917 let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone())918 .checked_sub(value)919 .unwrap();920 <Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);921922 let mut new_owner_account_id = 0;923 let new_owner_items = <AddressTokens<T>>::get(collection_id, new_owner.clone());924 if new_owner_items.len() > 0 {925 new_owner_account_id = new_owner_items[0];926 }927928 let val64 = value.into();929930 // transfer931 if amount == val64 && new_owner_account_id == 0 {932 // change owner933 // new owner do not have account934 let mut new_full_item = full_item.clone();935 new_full_item.owner = new_owner.clone();936 <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);937938 // update balance939 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())940 .checked_add(value)941 .unwrap();942 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);943944 // update index collection945 Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;946 } else {947 let mut new_full_item = full_item.clone();948 new_full_item.value -= val64;949950 // separate amount951 if new_owner_account_id > 0 {952 // new owner has account953 let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);954 item.value += val64;955956 // update balance957 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())958 .checked_add(value)959 .unwrap();960 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);961962 <FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);963 } else {964 // new owner do not have account965 let item = FungibleItemType {966 collection: collection_id,967 owner: new_owner.clone(),968 value: val64,969 };970971 Self::add_fungible_item(item)?;972 }973974 if amount == val64 {975 Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;976977 // remove approve list978 <ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));979 <FungibleItemList<T>>::remove(collection_id, item_id);980 }981982 <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);983 }984985 Ok(())986 }987988 fn transfer_refungible(989 collection_id: u64,990 item_id: u64,991 value: u64,992 owner: T::AccountId,993 new_owner: T::AccountId,994 ) -> DispatchResult {995996 ensure!(997 <ReFungibleItemList<T>>::contains_key(collection_id, item_id),998 "Item not exists"999 );10001001 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);1002 let item = full_item1003 .owner1004 .iter()1005 .filter(|i| i.owner == owner)1006 .next()1007 .unwrap();1008 let amount = item.fraction;10091010 ensure!(amount >= value.into(), "Item balance not enouth");10111012 // update balance1013 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1014 .checked_sub(value)1015 .unwrap();1016 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);10171018 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1019 .checked_add(value)1020 .unwrap();1021 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);10221023 let old_owner = item.owner.clone();1024 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);1025 let val64 = value.into();10261027 // transfer1028 if amount == val64 && !new_owner_has_account {1029 // change owner1030 // new owner do not have account1031 let mut new_full_item = full_item.clone();1032 new_full_item1033 .owner1034 .iter_mut()1035 .find(|i| i.owner == owner)1036 .unwrap()1037 .owner = new_owner.clone();1038 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);10391040 // update index collection1041 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;1042 } else {1043 let mut new_full_item = full_item.clone();1044 new_full_item1045 .owner1046 .iter_mut()1047 .find(|i| i.owner == owner)1048 .unwrap()1049 .fraction -= val64;10501051 // separate amount1052 if new_owner_has_account {1053 // new owner has account1054 new_full_item1055 .owner1056 .iter_mut()1057 .find(|i| i.owner == new_owner)1058 .unwrap()1059 .fraction += val64;1060 } else {1061 // new owner do not have account1062 new_full_item.owner.push(Ownership {1063 owner: new_owner.clone(),1064 fraction: val64,1065 });1066 Self::add_token_index(collection_id, item_id, new_owner.clone())?;1067 }10681069 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);1070 }10711072 Ok(())1073 }10741075 fn transfer_nft(1076 collection_id: u64,1077 item_id: u64,1078 sender: T::AccountId,1079 new_owner: T::AccountId,1080 ) -> DispatchResult {1081 1082 ensure!(1083 <NftItemList<T>>::contains_key(collection_id, item_id),1084 "Item not exists"1085 );10861087 let mut item = <NftItemList<T>>::get(collection_id, item_id);10881089 ensure!(1090 sender == item.owner,1091 "sender parameter and item owner must be equal"1092 );10931094 // update balance1095 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1096 .checked_sub(1)1097 .unwrap();1098 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);10991100 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1101 .checked_add(1)1102 .unwrap();1103 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);11041105 // change owner1106 let old_owner = item.owner.clone();1107 item.owner = new_owner.clone();1108 <NftItemList<T>>::insert(collection_id, item_id, item);11091110 // update index collection1111 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;11121113 // reset approved list1114 <ApprovedList<T>>::remove(collection_id, (item_id, old_owner));1115 Ok(())1116 }11171118 fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {1119 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1120 if list_exists {1121 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1122 let item_contains = list.contains(&item_index.clone());11231124 if !item_contains {1125 list.push(item_index.clone());1126 }11271128 <AddressTokens<T>>::insert(collection_id, owner.clone(), list);1129 } else {1130 let mut itm = Vec::new();1131 itm.push(item_index.clone());1132 <AddressTokens<T>>::insert(collection_id, owner, itm);1133 }11341135 Ok(())1136 }11371138 fn remove_token_index(1139 collection_id: u64,1140 item_index: u64,1141 owner: T::AccountId,1142 ) -> DispatchResult {1143 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1144 if list_exists {1145 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1146 let item_contains = list.contains(&item_index.clone());11471148 if item_contains {1149 list.retain(|&item| item != item_index);1150 <AddressTokens<T>>::insert(collection_id, owner, list);1151 }1152 }11531154 Ok(())1155 }11561157 fn move_token_index(1158 collection_id: u64,1159 item_index: u64,1160 old_owner: T::AccountId,1161 new_owner: T::AccountId,1162 ) -> DispatchResult {1163 Self::remove_token_index(collection_id, item_index, old_owner)?;1164 Self::add_token_index(collection_id, item_index, new_owner)?;11651166 Ok(())1167 }1168}11691170////////////////////////////////////////////////////////////////////////////////////////////////////1171// Economic models11721173/// Fee multiplier.1174pub type Multiplier = FixedU128;11751176type BalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1177 <T as system::Trait>::AccountId,1178>>::Balance;1179type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1180 <T as system::Trait>::AccountId,1181>>::NegativeImbalance;11821183/// Require the transactor pay for themselves and maybe include a tip to gain additional priority1184/// in the queue.1185#[derive(Encode, Decode, Clone, Eq, PartialEq)]1186pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(1187 #[codec(compact)] BalanceOf<T>,1188);11891190impl<T: Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug1191 for ChargeTransactionPayment<T>1192{1193 #[cfg(feature = "std")]1194 fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1195 write!(f, "ChargeTransactionPayment<{:?}>", self.0)1196 }1197 #[cfg(not(feature = "std"))]1198 fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1199 Ok(())1200 }1201}12021203impl<T: Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T>1204where1205 T::Call:1206 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1207 BalanceOf<T>: Send + Sync + FixedPointOperand,1208{1209 /// utility constructor. Used only in client/factory code.1210 pub fn from(fee: BalanceOf<T>) -> Self {1211 Self(fee)1212 }12131214 pub fn traditional_fee(1215 len: usize,1216 info: &DispatchInfoOf<T::Call>,1217 tip: BalanceOf<T>,1218 ) -> BalanceOf<T>1219 where1220 T::Call: Dispatchable<Info = DispatchInfo>,1221 {1222 <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)1223 }12241225 fn withdraw_fee(1226 &self,1227 who: &T::AccountId,1228 call: &T::Call,1229 info: &DispatchInfoOf<T::Call>,1230 len: usize,1231 ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {1232 let tip = self.0;12331234 // Set fee based on call type. Creating collection costs 1 Unique.1235 // All other transactions have traditional fees so far1236 let fee = match call.is_sub_type() {1237 Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1238 _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes1239 // _ => <BalanceOf<T>>::from(100)1240 };12411242 // Determine who is paying transaction fee based on ecnomic model1243 // Parse call to extract collection ID and access collection sponsor1244 let sponsor: T::AccountId = match call.is_sub_type() {1245 Some(Call::create_item(collection_id, _properties, _owner)) => {1246 <Collection<T>>::get(collection_id).sponsor1247 }1248 Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {1249 <Collection<T>>::get(collection_id).sponsor1250 }12511252 _ => T::AccountId::default(),1253 };12541255 let mut who_pays_fee: T::AccountId = sponsor.clone();1256 if sponsor == T::AccountId::default() {1257 who_pays_fee = who.clone();1258 }12591260 // Only mess with balances if fee is not zero.1261 if fee.is_zero() {1262 return Ok((fee, None));1263 }12641265 match <T as transaction_payment::Trait>::Currency::withdraw(1266 &who_pays_fee,1267 fee,1268 if tip.is_zero() {1269 WithdrawReason::TransactionPayment.into()1270 } else {1271 WithdrawReason::TransactionPayment | WithdrawReason::Tip1272 },1273 ExistenceRequirement::KeepAlive,1274 ) {1275 Ok(imbalance) => Ok((fee, Some(imbalance))),1276 Err(_) => Err(InvalidTransaction::Payment.into()),1277 }1278 }1279}12801281impl<T: Trait + transaction_payment::Trait + Send + Sync> SignedExtension1282 for ChargeTransactionPayment<T>1283where1284 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,1285 T::Call:1286 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1287{1288 const IDENTIFIER: &'static str = "ChargeTransactionPayment";1289 type AccountId = T::AccountId;1290 type Call = T::Call;1291 type AdditionalSigned = ();1292 type Pre = (1293 BalanceOf<T>,1294 Self::AccountId,1295 Option<NegativeImbalanceOf<T>>,1296 BalanceOf<T>,1297 );1298 fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {1299 Ok(())1300 }13011302 fn validate(1303 &self,1304 who: &Self::AccountId,1305 call: &Self::Call,1306 info: &DispatchInfoOf<Self::Call>,1307 len: usize,1308 ) -> TransactionValidity {1309 let (fee, _) = self.withdraw_fee(who, call, info, len)?;13101311 let mut r = ValidTransaction::default();1312 // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which1313 // will be a bit more than setting the priority to tip. For now, this is enough.1314 r.priority = fee.saturated_into::<TransactionPriority>();1315 Ok(r)1316 }13171318 fn pre_dispatch(1319 self,1320 who: &Self::AccountId,1321 call: &Self::Call,1322 info: &DispatchInfoOf<Self::Call>,1323 len: usize,1324 ) -> Result<Self::Pre, TransactionValidityError> {1325 let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;1326 Ok((self.0, who.clone(), imbalance, fee))1327 }13281329 fn post_dispatch(1330 pre: Self::Pre,1331 info: &DispatchInfoOf<Self::Call>,1332 post_info: &PostDispatchInfoOf<Self::Call>,1333 len: usize,1334 _result: &DispatchResult,1335 ) -> Result<(), TransactionValidityError> {1336 let (tip, who, imbalance, fee) = pre;1337 if let Some(payed) = imbalance {1338 let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(1339 len as u32, info, post_info, tip,1340 );1341 let refund = fee.saturating_sub(actual_fee);1342 let actual_payment =1343 match <T as transaction_payment::Trait>::Currency::deposit_into_existing(1344 &who, refund,1345 ) {1346 Ok(refund_imbalance) => {1347 // The refund cannot be larger than the up front payed max weight.1348 // `PostDispatchInfo::calc_unspent` guards against such a case.1349 match payed.offset(refund_imbalance) {1350 Ok(actual_payment) => actual_payment,1351 Err(_) => return Err(InvalidTransaction::Payment.into()),1352 }1353 }1354 // We do not recreate the account using the refund. The up front payment1355 // is gone in that case.1356 Err(_) => payed,1357 };1358 let imbalances = actual_payment.split(tip);1359 <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(1360 Some(imbalances.0).into_iter().chain(Some(imbalances.1)),1361 );1362 }1363 Ok(())1364 }1365}pallets/nft/src/tests.rsdiffbeforeafterboth--- a/pallets/nft/src/tests.rs
+++ b/pallets/nft/src/tests.rs
@@ -1,6 +1,6 @@
// Tests to be written here
use crate::mock::*;
-use crate::{ApprovePermissions, CollectionMode, Ownership};
+use crate::{ApprovePermissions, CollectionMode, AccessMode, Ownership};
use frame_support::{assert_noop, assert_ok};
#[test]
@@ -321,10 +321,11 @@
assert_eq!(TemplateModule::balance_count(1, 1), 1);
assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
- assert_noop!(
- TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),
- "You do not have permissions to modify this collection"
- );
+ assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+ assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+ assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+ assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+ assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));
// do approve
assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
@@ -390,10 +391,11 @@
assert_eq!(TemplateModule::balance_count(1, 1), 1000);
assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
- assert_noop!(
- TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),
- "You do not have permissions to modify this collection"
- );
+ assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+ assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+ assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+ assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+ assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));
// do approve
assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
@@ -461,10 +463,11 @@
assert_eq!(TemplateModule::balance_count(1, 1), 1000);
assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
- assert_noop!(
- TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),
- "You do not have permissions to modify this collection"
- );
+ assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+ assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+ assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+ assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+ assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));
// do approve
assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
@@ -573,7 +576,6 @@
let mode: CollectionMode = CollectionMode::NFT(2000);
let origin1 = Origin::signed(1);
- let origin2 = Origin::signed(2);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
col_name1.clone(),
@@ -583,7 +585,7 @@
));
assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
assert_ok!(TemplateModule::create_item(
- origin2.clone(),
+ origin1.clone(),
1,
[1, 2, 3].to_vec(),
1
@@ -614,7 +616,6 @@
let mode: CollectionMode = CollectionMode::Fungible(3);
let origin1 = Origin::signed(1);
- let origin2 = Origin::signed(2);
assert_ok!(TemplateModule::create_collection(
origin1.clone(),
col_name1.clone(),
@@ -624,7 +625,7 @@
));
assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
assert_ok!(TemplateModule::create_item(
- origin2.clone(),
+ origin1.clone(),
1,
[].to_vec(),
1
@@ -661,6 +662,11 @@
token_prefix1.clone(),
mode
));
+
+ assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+ assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+ assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+
assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
assert_ok!(TemplateModule::create_item(
origin2.clone(),
@@ -928,6 +934,13 @@
// approve
assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
assert_eq!(TemplateModule::approved(1, (1, 1))[0].approved, 2);
+
+ assert_ok!(TemplateModule::set_mint_permission(origin1.clone(), 1, true));
+ assert_ok!(TemplateModule::set_public_access_mode(origin1.clone(), 1, AccessMode::WhiteList));
+ assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
+ assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));
+ assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));
+
assert_ok!(TemplateModule::transfer_from(
origin2.clone(),
1,
runtime/src/lib.rsdiffbeforeafterboth--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -111,7 +111,7 @@
spec_name: create_runtime_str!("nft"),
impl_name: create_runtime_str!("nft"),
authoring_version: 1,
- spec_version: 1,
+ spec_version: 2,
impl_version: 1,
apis: RUNTIME_API_VERSIONS,
transaction_version: 1,