difftreelog
panic marcos removed
in: master
2 files changed
README.mddiffbeforeafterboth--- a/README.md
+++ b/README.md
@@ -109,6 +109,12 @@
"enable_println": "bool",
"max_subject_len": "u32"
},
+ "AccessMode": {
+ "_enum": [
+ "Normal",
+ "WhiteList"
+ ]
+ },
"CollectionMode": {
"_enum": {
"Invalid": null,
@@ -139,7 +145,7 @@
"CollectionType": {
"Owner": "AccountId",
"Mode": "CollectionMode",
- "Access": "u8",
+ "Access": "AccessMode",
"DecimalPoints": "u32",
"Name": "Vec<u16>",
"Description": "Vec<u16>",
@@ -155,4 +161,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 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 if target_collection.mint_mode == false {479 panic!("Collection is not in mint mode");480 }481482 Self::check_white_list(collection_id, owner.clone())?;483 }484485 match target_collection.mode486 {487 CollectionMode::NFT(_) => {488489 // check size490 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");491492 // Create nft item493 let item = NftItemType {494 collection: collection_id,495 owner: owner,496 data: properties,497 };498499 Self::add_nft_item(item)?;500501 },502 CollectionMode::Fungible(_) => {503504 // check size505 ensure!(properties.len() as u32 == 0, "Size of item must be 0 with fungible type");506507 let item = FungibleItemType {508 collection: collection_id,509 owner: owner,510 value: (10 as u128).pow(target_collection.decimal_points)511 };512513 Self::add_fungible_item(item)?;514 },515 CollectionMode::ReFungible(_, _) => {516517 // check size518 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");519520 let mut owner_list = Vec::new();521 let value = (10 as u128).pow(target_collection.decimal_points);522 owner_list.push(Ownership {owner: owner, fraction: value});523524 let item = ReFungibleItemType {525 collection: collection_id,526 owner: owner_list,527 data: properties528 };529530 Self::add_refungible_item(item)?;531 },532 _ => ()533 };534535 // call event536 Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));537538 Ok(())539 }540541 #[weight = 0]542 pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {543544 let sender = ensure_signed(origin)?;545 Self::collection_exists(collection_id)?;546 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);547 if !item_owner548 {549 if !Self::is_owner_or_admin_permissions(collection_id, sender.clone()) { 550 Self::check_white_list(collection_id, sender.clone())?;551 }552 }553 let target_collection = <Collection<T>>::get(collection_id);554555 match target_collection.mode556 {557 CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,558 CollectionMode::Fungible(_) => Self::burn_fungible_item(collection_id, item_id)?,559 CollectionMode::ReFungible(_, _) => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,560 _ => ()561 };562563 // call event564 Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));565566 Ok(())567 }568569 #[weight = 0]570 pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {571572 let sender = ensure_signed(origin)?;573574 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);575 if !item_owner {576 Self::check_white_list(collection_id, sender.clone())?;577 Self::check_white_list(collection_id, recipient.clone())?;578 }579580 let target_collection = <Collection<T>>::get(collection_id);581582 match target_collection.mode583 {584 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,585 CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,586 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,587 _ => ()588 };589590 Ok(())591 }592593 #[weight = 0]594 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {595596 let sender = ensure_signed(origin)?;597598 // amount param stub599 let amount = 100000000;600601 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);602 if !item_owner {603 Self::check_white_list(collection_id, approved.clone())?;604 }605606 let list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, sender.clone()));607 if list_exists {608609 let mut list = <ApprovedList<T>>::get(collection_id, (item_id, sender.clone()));610 let item_contains = list.iter().any(|i| i.approved == approved);611612 if !item_contains {613 list.push(ApprovePermissions { approved: approved.clone(), amount: amount });614 <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);615 }616 } else {617618 let mut list = Vec::new();619 list.push(ApprovePermissions { approved: approved.clone(), amount: amount });620 <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);621 }622623 Ok(())624 }625626 #[weight = 0]627 pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {628629 let sender = ensure_signed(origin)?;630 let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, from.clone()));631 if approved_list_exists632 {633 Self::check_white_list(collection_id, from.clone())?;634 Self::check_white_list(collection_id, recipient.clone())?;635636 let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));637 let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());638 ensure!(opt_item.is_some(), "No approve found");639 ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved");640641 // remove approve642 let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))643 .into_iter().filter(|i| i.approved != sender.clone()).collect();644 <ApprovedList<T>>::insert(collection_id, (item_id, from.clone()), approve_list);645 }646 else647 {648 panic!("Only approved addresses can call this method");649 }650651 let target_collection = <Collection<T>>::get(collection_id);652653 match target_collection.mode654 {655 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,656 CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, item_id, value, from.clone(), recipient)?,657 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,658 _ => ()659 };660661 Ok(())662 }663664 #[weight = 0]665 pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {666667 // let no_perm_mes = "You do not have permissions to modify this collection";668 // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);669 // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));670 // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);671672 // // on_nft_received call673674 // Self::transfer(origin, collection_id, item_id, new_owner)?;675676 Ok(())677 }678679 #[weight = 0]680 pub fn set_offchain_schema(681 origin,682 collection_id: u64,683 schema: Vec<u8>684 ) -> DispatchResult {685 let sender = ensure_signed(origin)?;686 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;687688 let mut target_collection = <Collection<T>>::get(collection_id);689 target_collection.offchain_schema = schema;690 <Collection<T>>::insert(collection_id, target_collection);691692 Ok(())693 }694 }695}696697impl<T: Trait> Module<T> {698 fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {699 let current_index = <ItemListIndex>::get(item.collection)700 .checked_add(1)701 .expect("Item list index id error");702 let itemcopy = item.clone();703 let owner = item.owner.clone();704 let value = item.value as u64;705706 Self::add_token_index(item.collection, current_index, owner.clone())?;707708 <ItemListIndex>::insert(item.collection, current_index);709 <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);710711 // Update balance712 let new_balance = <Balance<T>>::get(item.collection, owner.clone())713 .checked_add(value)714 .unwrap();715 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);716717 Ok(())718 }719720 fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {721 let current_index = <ItemListIndex>::get(item.collection)722 .checked_add(1)723 .expect("Item list index id error");724 let itemcopy = item.clone();725726 let value = item.owner.first().unwrap().fraction as u64;727 let owner = item.owner.first().unwrap().owner.clone();728729 Self::add_token_index(item.collection, current_index, owner.clone())?;730731 <ItemListIndex>::insert(item.collection, current_index);732 <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);733734 // Update balance735 let new_balance = <Balance<T>>::get(item.collection, owner.clone())736 .checked_add(value)737 .unwrap();738 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);739740 Ok(())741 }742743 fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {744 let current_index = <ItemListIndex>::get(item.collection)745 .checked_add(1)746 .expect("Item list index id error");747748 let item_owner = item.owner.clone();749 let collection_id = item.collection.clone();750 Self::add_token_index(collection_id, current_index, item.owner.clone())?;751752 <ItemListIndex>::insert(collection_id, current_index);753 <NftItemList<T>>::insert(collection_id, current_index, item);754755 // Update balance756 let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())757 .checked_add(1)758 .unwrap();759 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);760761 Ok(())762 }763764 fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {765 ensure!(766 <ReFungibleItemList<T>>::contains_key(collection_id, item_id),767 "Item does not exists"768 );769 let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);770 let item = collection771 .owner772 .iter()773 .filter(|&i| i.owner == owner)774 .next()775 .unwrap();776 Self::remove_token_index(collection_id, item_id, owner.clone())?;777778 // remove approve list779 <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));780781 // update balance782 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())783 .checked_sub(item.fraction as u64)784 .unwrap();785 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);786787 <ReFungibleItemList<T>>::remove(collection_id, item_id);788789 Ok(())790 }791792 fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {793 ensure!(794 <NftItemList<T>>::contains_key(collection_id, item_id),795 "Item does not exists"796 );797 let item = <NftItemList<T>>::get(collection_id, item_id);798 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;799800 // remove approve list801 <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));802803 // update balance804 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())805 .checked_sub(1)806 .unwrap();807 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);808 <NftItemList<T>>::remove(collection_id, item_id);809810 Ok(())811 }812813 fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {814 ensure!(815 <FungibleItemList<T>>::contains_key(collection_id, item_id),816 "Item does not exists"817 );818 let item = <FungibleItemList<T>>::get(collection_id, item_id);819 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;820821 // remove approve list822 <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));823824 // update balance825 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())826 .checked_sub(item.value as u64)827 .unwrap();828 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);829830 <FungibleItemList<T>>::remove(collection_id, item_id);831832 Ok(())833 }834835 fn collection_exists(collection_id: u64) -> DispatchResult {836 ensure!(837 <Collection<T>>::contains_key(collection_id),838 "This collection does not exist"839 );840 Ok(())841 }842843 fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {844 Self::collection_exists(collection_id)?;845846 let target_collection = <Collection<T>>::get(collection_id);847 ensure!(848 subject == target_collection.owner,849 "You do not own this collection"850 );851852 Ok(())853 }854855 fn is_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> bool {856857 let target_collection = <Collection<T>>::get(collection_id);858 let mut result: bool = subject == target_collection.owner;859 let exists = <AdminList<T>>::contains_key(collection_id);860861 if !result & exists {862 if <AdminList<T>>::get(collection_id).contains(&subject) {863 result = true864 }865 }866867 result868 }869870 fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {871 872 Self::collection_exists(collection_id)?;873 let result = Self::is_owner_or_admin_permissions(collection_id, subject.clone());874875 if result == true {876 Ok(())877 } else {878 panic!("You do not have permissions to modify this collection")879 }880 }881882 fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool {883 let target_collection = <Collection<T>>::get(collection_id);884885 match target_collection.mode {886 CollectionMode::NFT(_) => {887 <NftItemList<T>>::get(collection_id, item_id).owner == subject888 }889 CollectionMode::Fungible(_) => {890 <FungibleItemList<T>>::get(collection_id, item_id).owner == subject891 }892 CollectionMode::ReFungible(_, _) => {893 <ReFungibleItemList<T>>::get(collection_id, item_id)894 .owner895 .iter()896 .any(|i| i.owner == subject)897 }898 CollectionMode::Invalid => false,899 }900 }901902 fn check_white_list(collection_id: u64, address: T::AccountId) -> DispatchResult {903904 let mes = "Address is not in white list";905 if <WhiteList<T>>::contains_key(collection_id){906 let wl = <WhiteList<T>>::get(collection_id);907 if !wl.contains(&address.clone()) {908 panic!(mes);909 }910 }911 else {912 panic!(mes);913 }914 Ok(())915 }916917 fn transfer_fungible(918 collection_id: u64,919 item_id: u64,920 value: u64,921 owner: T::AccountId,922 new_owner: T::AccountId,923 ) -> DispatchResult {924925 ensure!(926 <FungibleItemList<T>>::contains_key(collection_id, item_id),927 "Item not exists"928 );929930 let full_item = <FungibleItemList<T>>::get(collection_id, item_id);931 let amount = full_item.value;932933 ensure!(amount >= value.into(), "Item balance not enouth");934935 // update balance936 let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone())937 .checked_sub(value)938 .unwrap();939 <Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);940941 let mut new_owner_account_id = 0;942 let new_owner_items = <AddressTokens<T>>::get(collection_id, new_owner.clone());943 if new_owner_items.len() > 0 {944 new_owner_account_id = new_owner_items[0];945 }946947 let val64 = value.into();948949 // transfer950 if amount == val64 && new_owner_account_id == 0 {951 // change owner952 // new owner do not have account953 let mut new_full_item = full_item.clone();954 new_full_item.owner = new_owner.clone();955 <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);956957 // update balance958 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())959 .checked_add(value)960 .unwrap();961 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);962963 // update index collection964 Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;965 } else {966 let mut new_full_item = full_item.clone();967 new_full_item.value -= val64;968969 // separate amount970 if new_owner_account_id > 0 {971 // new owner has account972 let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);973 item.value += val64;974975 // update balance976 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())977 .checked_add(value)978 .unwrap();979 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);980981 <FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);982 } else {983 // new owner do not have account984 let item = FungibleItemType {985 collection: collection_id,986 owner: new_owner.clone(),987 value: val64,988 };989990 Self::add_fungible_item(item)?;991 }992993 if amount == val64 {994 Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;995996 // remove approve list997 <ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));998 <FungibleItemList<T>>::remove(collection_id, item_id);999 }10001001 <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);1002 }10031004 Ok(())1005 }10061007 fn transfer_refungible(1008 collection_id: u64,1009 item_id: u64,1010 value: u64,1011 owner: T::AccountId,1012 new_owner: T::AccountId,1013 ) -> DispatchResult {10141015 ensure!(1016 <ReFungibleItemList<T>>::contains_key(collection_id, item_id),1017 "Item not exists"1018 );10191020 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);1021 let item = full_item1022 .owner1023 .iter()1024 .filter(|i| i.owner == owner)1025 .next()1026 .unwrap();1027 let amount = item.fraction;10281029 ensure!(amount >= value.into(), "Item balance not enouth");10301031 // update balance1032 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1033 .checked_sub(value)1034 .unwrap();1035 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);10361037 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1038 .checked_add(value)1039 .unwrap();1040 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);10411042 let old_owner = item.owner.clone();1043 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);1044 let val64 = value.into();10451046 // transfer1047 if amount == val64 && !new_owner_has_account {1048 // change owner1049 // new owner do not have account1050 let mut new_full_item = full_item.clone();1051 new_full_item1052 .owner1053 .iter_mut()1054 .find(|i| i.owner == owner)1055 .unwrap()1056 .owner = new_owner.clone();1057 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);10581059 // update index collection1060 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;1061 } else {1062 let mut new_full_item = full_item.clone();1063 new_full_item1064 .owner1065 .iter_mut()1066 .find(|i| i.owner == owner)1067 .unwrap()1068 .fraction -= val64;10691070 // separate amount1071 if new_owner_has_account {1072 // new owner has account1073 new_full_item1074 .owner1075 .iter_mut()1076 .find(|i| i.owner == new_owner)1077 .unwrap()1078 .fraction += val64;1079 } else {1080 // new owner do not have account1081 new_full_item.owner.push(Ownership {1082 owner: new_owner.clone(),1083 fraction: val64,1084 });1085 Self::add_token_index(collection_id, item_id, new_owner.clone())?;1086 }10871088 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);1089 }10901091 Ok(())1092 }10931094 fn transfer_nft(1095 collection_id: u64,1096 item_id: u64,1097 sender: T::AccountId,1098 new_owner: T::AccountId,1099 ) -> DispatchResult {1100 1101 ensure!(1102 <NftItemList<T>>::contains_key(collection_id, item_id),1103 "Item not exists"1104 );11051106 let mut item = <NftItemList<T>>::get(collection_id, item_id);11071108 ensure!(1109 sender == item.owner,1110 "sender parameter and item owner must be equal"1111 );11121113 // update balance1114 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1115 .checked_sub(1)1116 .unwrap();1117 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);11181119 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1120 .checked_add(1)1121 .unwrap();1122 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);11231124 // change owner1125 let old_owner = item.owner.clone();1126 item.owner = new_owner.clone();1127 <NftItemList<T>>::insert(collection_id, item_id, item);11281129 // update index collection1130 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;11311132 // reset approved list1133 <ApprovedList<T>>::remove(collection_id, (item_id, old_owner));1134 Ok(())1135 }11361137 fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {1138 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1139 if list_exists {1140 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1141 let item_contains = list.contains(&item_index.clone());11421143 if !item_contains {1144 list.push(item_index.clone());1145 }11461147 <AddressTokens<T>>::insert(collection_id, owner.clone(), list);1148 } else {1149 let mut itm = Vec::new();1150 itm.push(item_index.clone());1151 <AddressTokens<T>>::insert(collection_id, owner, itm);1152 }11531154 Ok(())1155 }11561157 fn remove_token_index(1158 collection_id: u64,1159 item_index: u64,1160 owner: T::AccountId,1161 ) -> DispatchResult {1162 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1163 if list_exists {1164 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1165 let item_contains = list.contains(&item_index.clone());11661167 if item_contains {1168 list.retain(|&item| item != item_index);1169 <AddressTokens<T>>::insert(collection_id, owner, list);1170 }1171 }11721173 Ok(())1174 }11751176 fn move_token_index(1177 collection_id: u64,1178 item_index: u64,1179 old_owner: T::AccountId,1180 new_owner: T::AccountId,1181 ) -> DispatchResult {1182 Self::remove_token_index(collection_id, item_index, old_owner)?;1183 Self::add_token_index(collection_id, item_index, new_owner)?;11841185 Ok(())1186 }1187}11881189////////////////////////////////////////////////////////////////////////////////////////////////////1190// Economic models11911192/// Fee multiplier.1193pub type Multiplier = FixedU128;11941195type BalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1196 <T as system::Trait>::AccountId,1197>>::Balance;1198type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1199 <T as system::Trait>::AccountId,1200>>::NegativeImbalance;12011202/// Require the transactor pay for themselves and maybe include a tip to gain additional priority1203/// in the queue.1204#[derive(Encode, Decode, Clone, Eq, PartialEq)]1205pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(1206 #[codec(compact)] BalanceOf<T>,1207);12081209impl<T: Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug1210 for ChargeTransactionPayment<T>1211{1212 #[cfg(feature = "std")]1213 fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1214 write!(f, "ChargeTransactionPayment<{:?}>", self.0)1215 }1216 #[cfg(not(feature = "std"))]1217 fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1218 Ok(())1219 }1220}12211222impl<T: Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T>1223where1224 T::Call:1225 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1226 BalanceOf<T>: Send + Sync + FixedPointOperand,1227{1228 /// utility constructor. Used only in client/factory code.1229 pub fn from(fee: BalanceOf<T>) -> Self {1230 Self(fee)1231 }12321233 pub fn traditional_fee(1234 len: usize,1235 info: &DispatchInfoOf<T::Call>,1236 tip: BalanceOf<T>,1237 ) -> BalanceOf<T>1238 where1239 T::Call: Dispatchable<Info = DispatchInfo>,1240 {1241 <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)1242 }12431244 fn withdraw_fee(1245 &self,1246 who: &T::AccountId,1247 call: &T::Call,1248 info: &DispatchInfoOf<T::Call>,1249 len: usize,1250 ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {1251 let tip = self.0;12521253 // Set fee based on call type. Creating collection costs 1 Unique.1254 // All other transactions have traditional fees so far1255 let fee = match call.is_sub_type() {1256 Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1257 _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes1258 // _ => <BalanceOf<T>>::from(100)1259 };12601261 // Determine who is paying transaction fee based on ecnomic model1262 // Parse call to extract collection ID and access collection sponsor1263 let sponsor: T::AccountId = match call.is_sub_type() {1264 Some(Call::create_item(collection_id, _properties, _owner)) => {1265 <Collection<T>>::get(collection_id).sponsor1266 }1267 Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {1268 <Collection<T>>::get(collection_id).sponsor1269 }12701271 _ => T::AccountId::default(),1272 };12731274 let mut who_pays_fee: T::AccountId = sponsor.clone();1275 if sponsor == T::AccountId::default() {1276 who_pays_fee = who.clone();1277 }12781279 // Only mess with balances if fee is not zero.1280 if fee.is_zero() {1281 return Ok((fee, None));1282 }12831284 match <T as transaction_payment::Trait>::Currency::withdraw(1285 &who_pays_fee,1286 fee,1287 if tip.is_zero() {1288 WithdrawReason::TransactionPayment.into()1289 } else {1290 WithdrawReason::TransactionPayment | WithdrawReason::Tip1291 },1292 ExistenceRequirement::KeepAlive,1293 ) {1294 Ok(imbalance) => Ok((fee, Some(imbalance))),1295 Err(_) => Err(InvalidTransaction::Payment.into()),1296 }1297 }1298}12991300impl<T: Trait + transaction_payment::Trait + Send + Sync> SignedExtension1301 for ChargeTransactionPayment<T>1302where1303 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,1304 T::Call:1305 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1306{1307 const IDENTIFIER: &'static str = "ChargeTransactionPayment";1308 type AccountId = T::AccountId;1309 type Call = T::Call;1310 type AdditionalSigned = ();1311 type Pre = (1312 BalanceOf<T>,1313 Self::AccountId,1314 Option<NegativeImbalanceOf<T>>,1315 BalanceOf<T>,1316 );1317 fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {1318 Ok(())1319 }13201321 fn validate(1322 &self,1323 who: &Self::AccountId,1324 call: &Self::Call,1325 info: &DispatchInfoOf<Self::Call>,1326 len: usize,1327 ) -> TransactionValidity {1328 let (fee, _) = self.withdraw_fee(who, call, info, len)?;13291330 let mut r = ValidTransaction::default();1331 // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which1332 // will be a bit more than setting the priority to tip. For now, this is enough.1333 r.priority = fee.saturated_into::<TransactionPriority>();1334 Ok(r)1335 }13361337 fn pre_dispatch(1338 self,1339 who: &Self::AccountId,1340 call: &Self::Call,1341 info: &DispatchInfoOf<Self::Call>,1342 len: usize,1343 ) -> Result<Self::Pre, TransactionValidityError> {1344 let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;1345 Ok((self.0, who.clone(), imbalance, fee))1346 }13471348 fn post_dispatch(1349 pre: Self::Pre,1350 info: &DispatchInfoOf<Self::Call>,1351 post_info: &PostDispatchInfoOf<Self::Call>,1352 len: usize,1353 _result: &DispatchResult,1354 ) -> Result<(), TransactionValidityError> {1355 let (tip, who, imbalance, fee) = pre;1356 if let Some(payed) = imbalance {1357 let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(1358 len as u32, info, post_info, tip,1359 );1360 let refund = fee.saturating_sub(actual_fee);1361 let actual_payment =1362 match <T as transaction_payment::Trait>::Currency::deposit_into_existing(1363 &who, refund,1364 ) {1365 Ok(refund_imbalance) => {1366 // The refund cannot be larger than the up front payed max weight.1367 // `PostDispatchInfo::calc_unspent` guards against such a case.1368 match payed.offset(refund_imbalance) {1369 Ok(actual_payment) => actual_payment,1370 Err(_) => return Err(InvalidTransaction::Payment.into()),1371 }1372 }1373 // We do not recreate the account using the refund. The up front payment1374 // is gone in that case.1375 Err(_) => payed,1376 };1377 let imbalances = actual_payment.split(tip);1378 <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(1379 Some(imbalances.0).into_iter().chain(Some(imbalances.1)),1380 );1381 }1382 Ok(())1383 }1384}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,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, fraction: value});520521 let item = ReFungibleItemType {522 collection: collection_id,523 owner: owner_list,524 data: properties525 };526527 Self::add_refungible_item(item)?;528 },529 _ => ()530 };531532 // call event533 Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));534535 Ok(())536 }537538 #[weight = 0]539 pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {540541 let sender = ensure_signed(origin)?;542 Self::collection_exists(collection_id)?;543 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);544 if !item_owner545 {546 if !Self::is_owner_or_admin_permissions(collection_id, sender.clone()) { 547 Self::check_white_list(collection_id, sender.clone())?;548 }549 }550 let target_collection = <Collection<T>>::get(collection_id);551552 match target_collection.mode553 {554 CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,555 CollectionMode::Fungible(_) => Self::burn_fungible_item(collection_id, item_id)?,556 CollectionMode::ReFungible(_, _) => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,557 _ => ()558 };559560 // call event561 Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));562563 Ok(())564 }565566 #[weight = 0]567 pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {568569 let sender = ensure_signed(origin)?;570571 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);572 if !item_owner {573 Self::check_white_list(collection_id, sender.clone())?;574 Self::check_white_list(collection_id, recipient.clone())?;575 }576577 let target_collection = <Collection<T>>::get(collection_id);578579 match target_collection.mode580 {581 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,582 CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,583 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,584 _ => ()585 };586587 Ok(())588 }589590 #[weight = 0]591 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {592593 let sender = ensure_signed(origin)?;594595 // amount param stub596 let amount = 100000000;597598 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);599 if !item_owner {600 Self::check_white_list(collection_id, approved.clone())?;601 }602603 let list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, sender.clone()));604 if list_exists {605606 let mut list = <ApprovedList<T>>::get(collection_id, (item_id, sender.clone()));607 let item_contains = list.iter().any(|i| i.approved == approved);608609 if !item_contains {610 list.push(ApprovePermissions { approved: approved.clone(), amount: amount });611 <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);612 }613 } else {614615 let mut list = Vec::new();616 list.push(ApprovePermissions { approved: approved.clone(), amount: amount });617 <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);618 }619620 Ok(())621 }622623 #[weight = 0]624 pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {625626 let sender = ensure_signed(origin)?;627 let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, from.clone()));628629 ensure!(approved_list_exists, "Only approved addresses can call this method");630631 Self::check_white_list(collection_id, from.clone())?;632 Self::check_white_list(collection_id, recipient.clone())?;633634 let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));635 let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());636 ensure!(opt_item.is_some(), "No approve found");637 ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved");638639 // remove approve640 let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))641 .into_iter().filter(|i| i.approved != sender.clone()).collect();642 <ApprovedList<T>>::insert(collection_id, (item_id, from.clone()), approve_list);643644 let target_collection = <Collection<T>>::get(collection_id);645646 match target_collection.mode647 {648 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,649 CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, item_id, value, from.clone(), recipient)?,650 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,651 _ => ()652 };653654 Ok(())655 }656657 #[weight = 0]658 pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {659660 // let no_perm_mes = "You do not have permissions to modify this collection";661 // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);662 // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));663 // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);664665 // // on_nft_received call666667 // Self::transfer(origin, collection_id, item_id, new_owner)?;668669 Ok(())670 }671672 #[weight = 0]673 pub fn set_offchain_schema(674 origin,675 collection_id: u64,676 schema: Vec<u8>677 ) -> DispatchResult {678 let sender = ensure_signed(origin)?;679 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;680681 let mut target_collection = <Collection<T>>::get(collection_id);682 target_collection.offchain_schema = schema;683 <Collection<T>>::insert(collection_id, target_collection);684685 Ok(())686 }687 }688}689690impl<T: Trait> Module<T> {691 fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {692 let current_index = <ItemListIndex>::get(item.collection)693 .checked_add(1)694 .expect("Item list index id error");695 let itemcopy = item.clone();696 let owner = item.owner.clone();697 let value = item.value as u64;698699 Self::add_token_index(item.collection, current_index, owner.clone())?;700701 <ItemListIndex>::insert(item.collection, current_index);702 <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);703704 // Update balance705 let new_balance = <Balance<T>>::get(item.collection, owner.clone())706 .checked_add(value)707 .unwrap();708 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);709710 Ok(())711 }712713 fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {714 let current_index = <ItemListIndex>::get(item.collection)715 .checked_add(1)716 .expect("Item list index id error");717 let itemcopy = item.clone();718719 let value = item.owner.first().unwrap().fraction as u64;720 let owner = item.owner.first().unwrap().owner.clone();721722 Self::add_token_index(item.collection, current_index, owner.clone())?;723724 <ItemListIndex>::insert(item.collection, current_index);725 <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);726727 // Update balance728 let new_balance = <Balance<T>>::get(item.collection, owner.clone())729 .checked_add(value)730 .unwrap();731 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);732733 Ok(())734 }735736 fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {737 let current_index = <ItemListIndex>::get(item.collection)738 .checked_add(1)739 .expect("Item list index id error");740741 let item_owner = item.owner.clone();742 let collection_id = item.collection.clone();743 Self::add_token_index(collection_id, current_index, item.owner.clone())?;744745 <ItemListIndex>::insert(collection_id, current_index);746 <NftItemList<T>>::insert(collection_id, current_index, item);747748 // Update balance749 let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())750 .checked_add(1)751 .unwrap();752 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);753754 Ok(())755 }756757 fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {758 ensure!(759 <ReFungibleItemList<T>>::contains_key(collection_id, item_id),760 "Item does not exists"761 );762 let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);763 let item = collection764 .owner765 .iter()766 .filter(|&i| i.owner == owner)767 .next()768 .unwrap();769 Self::remove_token_index(collection_id, item_id, owner.clone())?;770771 // remove approve list772 <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));773774 // update balance775 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())776 .checked_sub(item.fraction as u64)777 .unwrap();778 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);779780 <ReFungibleItemList<T>>::remove(collection_id, item_id);781782 Ok(())783 }784785 fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {786 ensure!(787 <NftItemList<T>>::contains_key(collection_id, item_id),788 "Item does not exists"789 );790 let item = <NftItemList<T>>::get(collection_id, item_id);791 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;792793 // remove approve list794 <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));795796 // update balance797 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())798 .checked_sub(1)799 .unwrap();800 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);801 <NftItemList<T>>::remove(collection_id, item_id);802803 Ok(())804 }805806 fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {807 ensure!(808 <FungibleItemList<T>>::contains_key(collection_id, item_id),809 "Item does not exists"810 );811 let item = <FungibleItemList<T>>::get(collection_id, item_id);812 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;813814 // remove approve list815 <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));816817 // update balance818 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())819 .checked_sub(item.value as u64)820 .unwrap();821 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);822823 <FungibleItemList<T>>::remove(collection_id, item_id);824825 Ok(())826 }827828 fn collection_exists(collection_id: u64) -> DispatchResult {829 ensure!(830 <Collection<T>>::contains_key(collection_id),831 "This collection does not exist"832 );833 Ok(())834 }835836 fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {837 Self::collection_exists(collection_id)?;838839 let target_collection = <Collection<T>>::get(collection_id);840 ensure!(841 subject == target_collection.owner,842 "You do not own this collection"843 );844845 Ok(())846 }847848 fn is_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> bool {849850 let target_collection = <Collection<T>>::get(collection_id);851 let mut result: bool = subject == target_collection.owner;852 let exists = <AdminList<T>>::contains_key(collection_id);853854 if !result & exists {855 if <AdminList<T>>::get(collection_id).contains(&subject) {856 result = true857 }858 }859860 result861 }862863 fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {864 865 Self::collection_exists(collection_id)?;866 let result = Self::is_owner_or_admin_permissions(collection_id, subject.clone());867868 ensure!(result, "You do not have permissions to modify this collection");869 Ok(())870 }871872 fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool {873 let target_collection = <Collection<T>>::get(collection_id);874875 match target_collection.mode {876 CollectionMode::NFT(_) => {877 <NftItemList<T>>::get(collection_id, item_id).owner == subject878 }879 CollectionMode::Fungible(_) => {880 <FungibleItemList<T>>::get(collection_id, item_id).owner == subject881 }882 CollectionMode::ReFungible(_, _) => {883 <ReFungibleItemList<T>>::get(collection_id, item_id)884 .owner885 .iter()886 .any(|i| i.owner == subject)887 }888 CollectionMode::Invalid => false,889 }890 }891892 fn check_white_list(collection_id: u64, address: T::AccountId) -> DispatchResult {893894 let mes = "Address is not in white list";895 ensure!(<WhiteList<T>>::contains_key(collection_id), mes);896 let wl = <WhiteList<T>>::get(collection_id);897 ensure!(wl.contains(&address.clone()), mes);898899 Ok(())900 }901902 fn transfer_fungible(903 collection_id: u64,904 item_id: u64,905 value: u64,906 owner: T::AccountId,907 new_owner: T::AccountId,908 ) -> DispatchResult {909910 ensure!(911 <FungibleItemList<T>>::contains_key(collection_id, item_id),912 "Item not exists"913 );914915 let full_item = <FungibleItemList<T>>::get(collection_id, item_id);916 let amount = full_item.value;917918 ensure!(amount >= value.into(), "Item balance not enouth");919920 // update balance921 let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone())922 .checked_sub(value)923 .unwrap();924 <Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);925926 let mut new_owner_account_id = 0;927 let new_owner_items = <AddressTokens<T>>::get(collection_id, new_owner.clone());928 if new_owner_items.len() > 0 {929 new_owner_account_id = new_owner_items[0];930 }931932 let val64 = value.into();933934 // transfer935 if amount == val64 && new_owner_account_id == 0 {936 // change owner937 // new owner do not have account938 let mut new_full_item = full_item.clone();939 new_full_item.owner = new_owner.clone();940 <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);941942 // update balance943 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())944 .checked_add(value)945 .unwrap();946 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);947948 // update index collection949 Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;950 } else {951 let mut new_full_item = full_item.clone();952 new_full_item.value -= val64;953954 // separate amount955 if new_owner_account_id > 0 {956 // new owner has account957 let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);958 item.value += val64;959960 // update balance961 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())962 .checked_add(value)963 .unwrap();964 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);965966 <FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);967 } else {968 // new owner do not have account969 let item = FungibleItemType {970 collection: collection_id,971 owner: new_owner.clone(),972 value: val64,973 };974975 Self::add_fungible_item(item)?;976 }977978 if amount == val64 {979 Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;980981 // remove approve list982 <ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));983 <FungibleItemList<T>>::remove(collection_id, item_id);984 }985986 <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);987 }988989 Ok(())990 }991992 fn transfer_refungible(993 collection_id: u64,994 item_id: u64,995 value: u64,996 owner: T::AccountId,997 new_owner: T::AccountId,998 ) -> DispatchResult {9991000 ensure!(1001 <ReFungibleItemList<T>>::contains_key(collection_id, item_id),1002 "Item not exists"1003 );10041005 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);1006 let item = full_item1007 .owner1008 .iter()1009 .filter(|i| i.owner == owner)1010 .next()1011 .unwrap();1012 let amount = item.fraction;10131014 ensure!(amount >= value.into(), "Item balance not enouth");10151016 // update balance1017 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1018 .checked_sub(value)1019 .unwrap();1020 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);10211022 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1023 .checked_add(value)1024 .unwrap();1025 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);10261027 let old_owner = item.owner.clone();1028 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);1029 let val64 = value.into();10301031 // transfer1032 if amount == val64 && !new_owner_has_account {1033 // change owner1034 // new owner do not have account1035 let mut new_full_item = full_item.clone();1036 new_full_item1037 .owner1038 .iter_mut()1039 .find(|i| i.owner == owner)1040 .unwrap()1041 .owner = new_owner.clone();1042 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);10431044 // update index collection1045 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;1046 } else {1047 let mut new_full_item = full_item.clone();1048 new_full_item1049 .owner1050 .iter_mut()1051 .find(|i| i.owner == owner)1052 .unwrap()1053 .fraction -= val64;10541055 // separate amount1056 if new_owner_has_account {1057 // new owner has account1058 new_full_item1059 .owner1060 .iter_mut()1061 .find(|i| i.owner == new_owner)1062 .unwrap()1063 .fraction += val64;1064 } else {1065 // new owner do not have account1066 new_full_item.owner.push(Ownership {1067 owner: new_owner.clone(),1068 fraction: val64,1069 });1070 Self::add_token_index(collection_id, item_id, new_owner.clone())?;1071 }10721073 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);1074 }10751076 Ok(())1077 }10781079 fn transfer_nft(1080 collection_id: u64,1081 item_id: u64,1082 sender: T::AccountId,1083 new_owner: T::AccountId,1084 ) -> DispatchResult {1085 1086 ensure!(1087 <NftItemList<T>>::contains_key(collection_id, item_id),1088 "Item not exists"1089 );10901091 let mut item = <NftItemList<T>>::get(collection_id, item_id);10921093 ensure!(1094 sender == item.owner,1095 "sender parameter and item owner must be equal"1096 );10971098 // update balance1099 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1100 .checked_sub(1)1101 .unwrap();1102 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);11031104 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1105 .checked_add(1)1106 .unwrap();1107 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);11081109 // change owner1110 let old_owner = item.owner.clone();1111 item.owner = new_owner.clone();1112 <NftItemList<T>>::insert(collection_id, item_id, item);11131114 // update index collection1115 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;11161117 // reset approved list1118 <ApprovedList<T>>::remove(collection_id, (item_id, old_owner));1119 Ok(())1120 }11211122 fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {1123 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1124 if list_exists {1125 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1126 let item_contains = list.contains(&item_index.clone());11271128 if !item_contains {1129 list.push(item_index.clone());1130 }11311132 <AddressTokens<T>>::insert(collection_id, owner.clone(), list);1133 } else {1134 let mut itm = Vec::new();1135 itm.push(item_index.clone());1136 <AddressTokens<T>>::insert(collection_id, owner, itm);1137 }11381139 Ok(())1140 }11411142 fn remove_token_index(1143 collection_id: u64,1144 item_index: u64,1145 owner: T::AccountId,1146 ) -> DispatchResult {1147 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1148 if list_exists {1149 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1150 let item_contains = list.contains(&item_index.clone());11511152 if item_contains {1153 list.retain(|&item| item != item_index);1154 <AddressTokens<T>>::insert(collection_id, owner, list);1155 }1156 }11571158 Ok(())1159 }11601161 fn move_token_index(1162 collection_id: u64,1163 item_index: u64,1164 old_owner: T::AccountId,1165 new_owner: T::AccountId,1166 ) -> DispatchResult {1167 Self::remove_token_index(collection_id, item_index, old_owner)?;1168 Self::add_token_index(collection_id, item_index, new_owner)?;11691170 Ok(())1171 }1172}11731174////////////////////////////////////////////////////////////////////////////////////////////////////1175// Economic models11761177/// Fee multiplier.1178pub type Multiplier = FixedU128;11791180type BalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1181 <T as system::Trait>::AccountId,1182>>::Balance;1183type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1184 <T as system::Trait>::AccountId,1185>>::NegativeImbalance;11861187/// Require the transactor pay for themselves and maybe include a tip to gain additional priority1188/// in the queue.1189#[derive(Encode, Decode, Clone, Eq, PartialEq)]1190pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(1191 #[codec(compact)] BalanceOf<T>,1192);11931194impl<T: Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug1195 for ChargeTransactionPayment<T>1196{1197 #[cfg(feature = "std")]1198 fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1199 write!(f, "ChargeTransactionPayment<{:?}>", self.0)1200 }1201 #[cfg(not(feature = "std"))]1202 fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1203 Ok(())1204 }1205}12061207impl<T: Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T>1208where1209 T::Call:1210 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1211 BalanceOf<T>: Send + Sync + FixedPointOperand,1212{1213 /// utility constructor. Used only in client/factory code.1214 pub fn from(fee: BalanceOf<T>) -> Self {1215 Self(fee)1216 }12171218 pub fn traditional_fee(1219 len: usize,1220 info: &DispatchInfoOf<T::Call>,1221 tip: BalanceOf<T>,1222 ) -> BalanceOf<T>1223 where1224 T::Call: Dispatchable<Info = DispatchInfo>,1225 {1226 <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)1227 }12281229 fn withdraw_fee(1230 &self,1231 who: &T::AccountId,1232 call: &T::Call,1233 info: &DispatchInfoOf<T::Call>,1234 len: usize,1235 ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {1236 let tip = self.0;12371238 // Set fee based on call type. Creating collection costs 1 Unique.1239 // All other transactions have traditional fees so far1240 let fee = match call.is_sub_type() {1241 Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1242 _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes1243 // _ => <BalanceOf<T>>::from(100)1244 };12451246 // Determine who is paying transaction fee based on ecnomic model1247 // Parse call to extract collection ID and access collection sponsor1248 let sponsor: T::AccountId = match call.is_sub_type() {1249 Some(Call::create_item(collection_id, _properties, _owner)) => {1250 <Collection<T>>::get(collection_id).sponsor1251 }1252 Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {1253 <Collection<T>>::get(collection_id).sponsor1254 }12551256 _ => T::AccountId::default(),1257 };12581259 let mut who_pays_fee: T::AccountId = sponsor.clone();1260 if sponsor == T::AccountId::default() {1261 who_pays_fee = who.clone();1262 }12631264 // Only mess with balances if fee is not zero.1265 if fee.is_zero() {1266 return Ok((fee, None));1267 }12681269 match <T as transaction_payment::Trait>::Currency::withdraw(1270 &who_pays_fee,1271 fee,1272 if tip.is_zero() {1273 WithdrawReason::TransactionPayment.into()1274 } else {1275 WithdrawReason::TransactionPayment | WithdrawReason::Tip1276 },1277 ExistenceRequirement::KeepAlive,1278 ) {1279 Ok(imbalance) => Ok((fee, Some(imbalance))),1280 Err(_) => Err(InvalidTransaction::Payment.into()),1281 }1282 }1283}12841285impl<T: Trait + transaction_payment::Trait + Send + Sync> SignedExtension1286 for ChargeTransactionPayment<T>1287where1288 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,1289 T::Call:1290 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1291{1292 const IDENTIFIER: &'static str = "ChargeTransactionPayment";1293 type AccountId = T::AccountId;1294 type Call = T::Call;1295 type AdditionalSigned = ();1296 type Pre = (1297 BalanceOf<T>,1298 Self::AccountId,1299 Option<NegativeImbalanceOf<T>>,1300 BalanceOf<T>,1301 );1302 fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {1303 Ok(())1304 }13051306 fn validate(1307 &self,1308 who: &Self::AccountId,1309 call: &Self::Call,1310 info: &DispatchInfoOf<Self::Call>,1311 len: usize,1312 ) -> TransactionValidity {1313 let (fee, _) = self.withdraw_fee(who, call, info, len)?;13141315 let mut r = ValidTransaction::default();1316 // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which1317 // will be a bit more than setting the priority to tip. For now, this is enough.1318 r.priority = fee.saturated_into::<TransactionPriority>();1319 Ok(r)1320 }13211322 fn pre_dispatch(1323 self,1324 who: &Self::AccountId,1325 call: &Self::Call,1326 info: &DispatchInfoOf<Self::Call>,1327 len: usize,1328 ) -> Result<Self::Pre, TransactionValidityError> {1329 let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;1330 Ok((self.0, who.clone(), imbalance, fee))1331 }13321333 fn post_dispatch(1334 pre: Self::Pre,1335 info: &DispatchInfoOf<Self::Call>,1336 post_info: &PostDispatchInfoOf<Self::Call>,1337 len: usize,1338 _result: &DispatchResult,1339 ) -> Result<(), TransactionValidityError> {1340 let (tip, who, imbalance, fee) = pre;1341 if let Some(payed) = imbalance {1342 let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(1343 len as u32, info, post_info, tip,1344 );1345 let refund = fee.saturating_sub(actual_fee);1346 let actual_payment =1347 match <T as transaction_payment::Trait>::Currency::deposit_into_existing(1348 &who, refund,1349 ) {1350 Ok(refund_imbalance) => {1351 // The refund cannot be larger than the up front payed max weight.1352 // `PostDispatchInfo::calc_unspent` guards against such a case.1353 match payed.offset(refund_imbalance) {1354 Ok(actual_payment) => actual_payment,1355 Err(_) => return Err(InvalidTransaction::Payment.into()),1356 }1357 }1358 // We do not recreate the account using the refund. The up front payment1359 // is gone in that case.1360 Err(_) => payed,1361 };1362 let imbalances = actual_payment.split(tip);1363 <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(1364 Some(imbalances.0).into_iter().chain(Some(imbalances.1)),1365 );1366 }1367 Ok(())1368 }1369}