1#![cfg_attr(not(feature = "std"), no_std)]23#[cfg(feature = "std")]4pub use serde::*;56use codec::{Decode, Encode};7pub use frame_support::{8 construct_runtime, decl_event, decl_module, decl_storage,9 dispatch::DispatchResult,10 ensure, parameter_types,11 traits::{12 Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,13 Randomness, WithdrawReason,14 },15 weights::{16 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},17 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,18 WeightToFeePolynomial,19 },20 IsSubType, StorageValue,21};2223use frame_system::{self as system, ensure_signed};24use sp_runtime::sp_std::prelude::Vec;25use sp_runtime::{26 traits::{27 DispatchInfoOf, Dispatchable, PostDispatchInfoOf, SaturatedConversion, Saturating,28 SignedExtension, Zero,29 },30 transaction_validity::{31 InvalidTransaction, TransactionPriority, TransactionValidity, TransactionValidityError,32 ValidTransaction,33 },34 FixedPointOperand, FixedU128,35};3637#[cfg(test)]38mod mock;3940#[cfg(test)]41mod tests;4243444546#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]47#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]48pub enum CollectionMode {49 Invalid,50 51 NFT(u32),52 53 Fungible(u32),54 55 ReFungible(u32, u32),56}5758impl Into<u8> for CollectionMode {59 fn into(self) -> u8 {60 match self {61 CollectionMode::Invalid => 0,62 CollectionMode::NFT(_) => 1,63 CollectionMode::Fungible(_) => 2,64 CollectionMode::ReFungible(_, _) => 3,65 }66 }67}6869#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq)]70#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]71pub enum AccessMode {72 Normal,73 WhiteList,74}75impl Default for AccessMode {76 fn default() -> Self {77 Self::Normal78 }79}8081impl Default for CollectionMode {82 fn default() -> Self {83 Self::Invalid84 }85}8687#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]88#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]89pub struct Ownership<AccountId> {90 pub owner: AccountId,91 pub fraction: u128,92}9394#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]95#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]96pub struct CollectionType<AccountId> {97 pub owner: AccountId,98 pub mode: CollectionMode,99 pub access: AccessMode,100 pub decimal_points: u32,101 pub name: Vec<u16>, 102 pub description: Vec<u16>, 103 pub token_prefix: Vec<u8>, 104 pub custom_data_size: u32,105 pub mint_mode: bool,106 pub offchain_schema: Vec<u8>,107 pub sponsor: AccountId, 108 pub unconfirmed_sponsor: AccountId, 109}110111#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]112#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]113pub struct CollectionAdminsType<AccountId> {114 pub admin: AccountId,115 pub collection_id: u64,116}117118#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]119#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]120pub struct NftItemType<AccountId> {121 pub collection: u64,122 pub owner: AccountId,123 pub data: Vec<u8>,124}125126#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]127#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]128pub struct FungibleItemType<AccountId> {129 pub collection: u64,130 pub owner: AccountId,131 pub value: u128,132}133134#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]135#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]136pub struct ReFungibleItemType<AccountId> {137 pub collection: u64,138 pub owner: Vec<Ownership<AccountId>>,139 pub data: Vec<u8>,140}141142#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]143#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]144pub struct ApprovePermissions<AccountId> {145 pub approved: AccountId,146 pub amount: u64,147}148149#[derive(Encode, Decode, Default, Debug, Clone, PartialEq)]150#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]151pub struct VestingItem<AccountId, Moment> {152 pub sender: AccountId,153 pub recipient: AccountId,154 pub collection_id: u64,155 pub item_id: u64,156 pub amount: u64,157 pub vesting_date: Moment,158}159160pub trait Trait: system::Trait {161 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;162}163164165166decl_storage! {167 trait Store for Module<T: Trait> as Nft {168169 170 NextCollectionID: u64;171 CreatedCollectionCount: u64;172 ChainVersion: u64;173 ItemListIndex: map hasher(blake2_128_concat) u64 => u64;174175 pub Collection get(fn collection) config(): map hasher(identity) u64 => CollectionType<T::AccountId>;176 pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;177 pub WhiteList get(fn white_list): map hasher(identity) u64 => Vec<T::AccountId>;178179 180 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;181182 183 pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) (u64, T::AccountId) => Vec<ApprovePermissions<T::AccountId>>;184185 186 pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;187 pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;188 pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;189190 191 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;192193 194 pub ContractSponsor get(fn contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;195 pub UnconfirmedContractSponsor get(fn unconfirmed_contract_sponsor): map hasher(identity) T::AccountId => T::AccountId;196 }197 add_extra_genesis {198 build(|config: &GenesisConfig<T>| {199 200 for (_num, _c) in &config.collection {201 <Module<T>>::init_collection(_c);202 }203204 for (_num, _q, _i) in &config.nft_item_id {205 <Module<T>>::init_nft_token(_i);206 }207208 for (_num, _q, _i) in &config.fungible_item_id {209 <Module<T>>::init_fungible_token(_i);210 }211212 for (_num, _q, _i) in &config.refungible_item_id {213 <Module<T>>::init_refungible_token(_i);214 }215 })216 }217}218219decl_event!(220 pub enum Event<T>221 where222 AccountId = <T as system::Trait>::AccountId,223 {224 Created(u64, u8, AccountId),225 ItemCreated(u64, u64),226 ItemDestroyed(u64, u64),227 }228);229230decl_module! {231 pub struct Module<T: Trait> for enum Call where origin: T::Origin {232233 fn deposit_event() = default;234235 fn on_initialize(now: T::BlockNumber) -> Weight {236237 if ChainVersion::get() < 2238 {239 let value = NextCollectionID::get();240 CreatedCollectionCount::put(value);241 ChainVersion::put(2);242 }243244 0245 }246247 248 249 250 251 #[weight = 0]252 pub fn create_collection(origin,253 collection_name: Vec<u16>,254 collection_description: Vec<u16>,255 token_prefix: Vec<u8>,256 mode: CollectionMode) -> DispatchResult {257258 259 let who = ensure_signed(origin)?;260 let custom_data_size = match mode {261 CollectionMode::NFT(size) => size,262 CollectionMode::ReFungible(size, _) => size,263 _ => 0264 };265266 let decimal_points = match mode {267 CollectionMode::Fungible(points) => points,268 CollectionMode::ReFungible(_, points) => points,269 _ => 0270 };271272 273 ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4");274275 let mut name = collection_name.to_vec();276 name.push(0);277 ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");278279 let mut description = collection_description.to_vec();280 description.push(0);281 ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");282283 let mut prefix = token_prefix.to_vec();284 prefix.push(0);285 ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");286287 288 let next_id = CreatedCollectionCount::get()289 .checked_add(1)290 .expect("collection id error");291292 CreatedCollectionCount::put(next_id);293294 295 let new_collection = CollectionType {296 owner: who.clone(),297 name: name,298 mode: mode.clone(),299 mint_mode: false,300 access: AccessMode::Normal,301 description: description,302 decimal_points: decimal_points,303 token_prefix: prefix,304 offchain_schema: Vec::new(),305 custom_data_size: custom_data_size,306 sponsor: T::AccountId::default(),307 unconfirmed_sponsor: T::AccountId::default(),308 };309310 311 <Collection<T>>::insert(next_id, new_collection);312313 314 Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));315316 Ok(())317 }318319 #[weight = 0]320 pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {321322 let sender = ensure_signed(origin)?;323 Self::check_owner_permissions(collection_id, sender)?;324325 326 <AddressTokens<T>>::remove_prefix(collection_id);327 <ApprovedList<T>>::remove_prefix(collection_id);328 <Balance<T>>::remove_prefix(collection_id);329 <ItemListIndex>::remove(collection_id);330 <AdminList<T>>::remove(collection_id);331 <Collection<T>>::remove(collection_id);332 <WhiteList<T>>::remove(collection_id);333334 Ok(())335 }336337 #[weight = 0]338 pub fn add_to_white_list(origin, collection_id: u64, address: T::AccountId) -> DispatchResult{339340 let sender = ensure_signed(origin)?;341 Self::check_owner_or_admin_permissions(collection_id, sender)?;342343 let mut white_list_collection: Vec<T::AccountId>;344 if <WhiteList<T>>::contains_key(collection_id) {345 white_list_collection = <WhiteList<T>>::get(collection_id);346 if !white_list_collection.contains(&address.clone())347 {348 white_list_collection.push(address.clone());349 }350 }351 else {352 white_list_collection = Vec::new();353 white_list_collection.push(address.clone());354 }355356 <WhiteList<T>>::insert(collection_id, white_list_collection);357 Ok(())358 }359360 #[weight = 0]361 pub fn remove_from_white_list(origin, collection_id: u64, address: T::AccountId) -> DispatchResult{362363 let sender = ensure_signed(origin)?;364 Self::check_owner_or_admin_permissions(collection_id, sender)?;365366 if <WhiteList<T>>::contains_key(collection_id) {367 let mut white_list_collection = <WhiteList<T>>::get(collection_id);368 if white_list_collection.contains(&address.clone())369 {370 white_list_collection.retain(|i| *i != address.clone());371 <WhiteList<T>>::insert(collection_id, white_list_collection);372 }373 }374375 Ok(())376 }377378 #[weight = 0]379 pub fn set_public_access_mode(origin, collection_id: u64, mode: AccessMode) -> DispatchResult380 {381 let sender = ensure_signed(origin)?;382383 Self::check_owner_permissions(collection_id, sender)?;384 let mut target_collection = <Collection<T>>::get(collection_id);385 target_collection.access = mode;386 <Collection<T>>::insert(collection_id, target_collection);387388 Ok(())389 }390391 #[weight = 0]392 pub fn set_mint_permission(origin, collection_id: u64, mint_permission: bool) -> DispatchResult393 {394 let sender = ensure_signed(origin)?;395396 Self::check_owner_permissions(collection_id, sender)?;397 let mut target_collection = <Collection<T>>::get(collection_id);398 target_collection.mint_mode = mint_permission;399 <Collection<T>>::insert(collection_id, target_collection);400401 Ok(())402 }403404 #[weight = 0]405 pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {406407 let sender = ensure_signed(origin)?;408 Self::check_owner_permissions(collection_id, sender)?;409 let mut target_collection = <Collection<T>>::get(collection_id);410 target_collection.owner = new_owner;411 <Collection<T>>::insert(collection_id, target_collection);412413 Ok(())414 }415416 #[weight = 0]417 pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {418419 let sender = ensure_signed(origin)?;420 Self::check_owner_or_admin_permissions(collection_id, sender)?;421 let mut admin_arr: Vec<T::AccountId> = Vec::new();422423 if <AdminList<T>>::contains_key(collection_id)424 {425 admin_arr = <AdminList<T>>::get(collection_id);426 ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");427 }428429 admin_arr.push(new_admin_id);430 <AdminList<T>>::insert(collection_id, admin_arr);431432 Ok(())433 }434435 #[weight = 0]436 pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {437438 let sender = ensure_signed(origin)?;439 Self::check_owner_or_admin_permissions(collection_id, sender)?;440441 if <AdminList<T>>::contains_key(collection_id)442 {443 let mut admin_arr = <AdminList<T>>::get(collection_id);444 admin_arr.retain(|i| *i != account_id);445 <AdminList<T>>::insert(collection_id, admin_arr);446 }447448 Ok(())449 }450451 #[weight = 0]452 pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {453454 let sender = ensure_signed(origin)?;455 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");456457 let mut target_collection = <Collection<T>>::get(collection_id);458 ensure!(sender == target_collection.owner, "You do not own this collection");459460 target_collection.unconfirmed_sponsor = new_sponsor;461 <Collection<T>>::insert(collection_id, target_collection);462463 Ok(())464 }465466 #[weight = 0]467 pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {468469 let sender = ensure_signed(origin)?;470 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");471472 let mut target_collection = <Collection<T>>::get(collection_id);473 ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");474475 target_collection.sponsor = target_collection.unconfirmed_sponsor;476 target_collection.unconfirmed_sponsor = T::AccountId::default();477 <Collection<T>>::insert(collection_id, target_collection);478479 Ok(())480 }481482 #[weight = 0]483 pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {484485 let sender = ensure_signed(origin)?;486 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");487488 let mut target_collection = <Collection<T>>::get(collection_id);489 ensure!(sender == target_collection.owner, "You do not own this collection");490491 target_collection.sponsor = T::AccountId::default();492 <Collection<T>>::insert(collection_id, target_collection);493494 Ok(())495 }496497 #[weight = 0]498 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {499500 let sender = ensure_signed(origin)?;501 Self::collection_exists(collection_id)?;502 let target_collection = <Collection<T>>::get(collection_id);503504 if !Self::is_owner_or_admin_permissions(collection_id, sender.clone()) {505 ensure!(target_collection.mint_mode == true, "Collection is not in mint mode");506 Self::check_white_list(collection_id, owner.clone())?;507 }508509 match target_collection.mode510 {511 CollectionMode::NFT(_) => {512513 514 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");515516 517 let item = NftItemType {518 collection: collection_id,519 owner: owner,520 data: properties.clone(),521 };522523 Self::add_nft_item(item)?;524525 },526 CollectionMode::Fungible(_) => {527528 529 ensure!(properties.len() as u32 == 0, "Size of item must be 0 with fungible type");530531 let item = FungibleItemType {532 collection: collection_id,533 owner: owner,534 value: (10 as u128).pow(target_collection.decimal_points)535 };536537 Self::add_fungible_item(item)?;538 },539 CollectionMode::ReFungible(_, _) => {540541 542 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");543544 let mut owner_list = Vec::new();545 let value = (10 as u128).pow(target_collection.decimal_points);546 owner_list.push(Ownership {owner: owner.clone(), fraction: value});547548 let item = ReFungibleItemType {549 collection: collection_id,550 owner: owner_list,551 data: properties.clone()552 };553554 Self::add_refungible_item(item)?;555 },556 _ => { ensure!(1 == 0,"just error"); }557558 };559560 561 Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));562563 Ok(())564 }565566 #[weight = 0]567 pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {568569 let sender = ensure_signed(origin)?;570 Self::collection_exists(collection_id)?;571572 573 let target_collection = <Collection<T>>::get(collection_id);574 ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) || 575 Self::is_owner_or_admin_permissions(collection_id, sender.clone()), 576 "Only item owner, collection owner and admins can modify item");577578 if target_collection.access == AccessMode::WhiteList {579 Self::check_white_list(collection_id, sender.clone())?;580 }581582 match target_collection.mode583 {584 CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,585 CollectionMode::Fungible(_) => Self::burn_fungible_item(collection_id, item_id)?,586 CollectionMode::ReFungible(_, _) => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,587 _ => ()588 };589590 591 Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));592593 Ok(())594 }595596 #[weight = 0]597 pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {598599 let sender = ensure_signed(origin)?;600601 602 let target_collection = <Collection<T>>::get(collection_id);603 ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) || 604 Self::is_owner_or_admin_permissions(collection_id, sender.clone()), 605 "Only item owner, collection owner and admins can modify item");606607 if target_collection.access == AccessMode::WhiteList {608 Self::check_white_list(collection_id, sender.clone())?;609 Self::check_white_list(collection_id, recipient.clone())?;610 }611612 match target_collection.mode613 {614 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,615 CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,616 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,617 _ => ()618 };619620 Ok(())621 }622623 #[weight = 0]624 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {625626 let sender = ensure_signed(origin)?;627628 629 let target_collection = <Collection<T>>::get(collection_id);630 ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) || 631 Self::is_owner_or_admin_permissions(collection_id, sender.clone()), 632 "Only item owner, collection owner and admins can approve");633634 if target_collection.access == AccessMode::WhiteList {635 Self::check_white_list(collection_id, sender.clone())?;636 Self::check_white_list(collection_id, approved.clone())?;637 }638639 640 let amount = 100000000;641642 let list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, sender.clone()));643 if list_exists {644645 let mut list = <ApprovedList<T>>::get(collection_id, (item_id, sender.clone()));646 let item_contains = list.iter().any(|i| i.approved == approved);647648 if !item_contains {649 list.push(ApprovePermissions { approved: approved.clone(), amount: amount });650 <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);651 }652 } else {653654 let mut list = Vec::new();655 list.push(ApprovePermissions { approved: approved.clone(), amount: amount });656 <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);657 }658659 Ok(())660 }661662 #[weight = 0]663 pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {664665 let sender = ensure_signed(origin)?;666 let mut appoved_transfer = false;667668 669 if <ApprovedList<T>>::contains_key(collection_id, (item_id, from.clone())) {670 let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));671 let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());672 appoved_transfer = opt_item.is_some();673 ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved");674 }675676 677 let target_collection = <Collection<T>>::get(collection_id);678 ensure!(appoved_transfer || Self::is_owner_or_admin_permissions(collection_id, sender.clone()), 679 "Only item owner, collection owner and admins can modify items");680681 if target_collection.access == AccessMode::WhiteList {682 Self::check_white_list(collection_id, sender.clone())?;683 Self::check_white_list(collection_id, recipient.clone())?;684 }685686 687 let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))688 .into_iter().filter(|i| i.approved != sender.clone()).collect();689 <ApprovedList<T>>::insert(collection_id, (item_id, from.clone()), approve_list);690691692 match target_collection.mode693 {694 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,695 CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, item_id, value, from.clone(), recipient)?,696 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,697 _ => ()698 };699700 Ok(())701 }702703 #[weight = 0]704 pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {705706 707 708 709 710711 712713 714715 Ok(())716 }717718 #[weight = 0]719 pub fn set_offchain_schema(720 origin,721 collection_id: u64,722 schema: Vec<u8>723 ) -> DispatchResult {724 let sender = ensure_signed(origin)?;725 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;726727 let mut target_collection = <Collection<T>>::get(collection_id);728 target_collection.offchain_schema = schema;729 <Collection<T>>::insert(collection_id, target_collection);730731 Ok(())732 }733 }734}735736impl<T: Trait> Module<T> {737 fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {738 let current_index = <ItemListIndex>::get(item.collection)739 .checked_add(1)740 .expect("Item list index id error");741 let itemcopy = item.clone();742 let owner = item.owner.clone();743 let value = item.value as u64;744745 Self::add_token_index(item.collection, current_index, owner.clone())?;746747 <ItemListIndex>::insert(item.collection, current_index);748 <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);749750 751 let new_balance = <Balance<T>>::get(item.collection, owner.clone())752 .checked_add(value)753 .unwrap();754 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);755756 Ok(())757 }758759 fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {760 let current_index = <ItemListIndex>::get(item.collection)761 .checked_add(1)762 .expect("Item list index id error");763 let itemcopy = item.clone();764765 let value = item.owner.first().unwrap().fraction as u64;766 let owner = item.owner.first().unwrap().owner.clone();767768 Self::add_token_index(item.collection, current_index, owner.clone())?;769770 <ItemListIndex>::insert(item.collection, current_index);771 <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);772773 774 let new_balance = <Balance<T>>::get(item.collection, owner.clone())775 .checked_add(value)776 .unwrap();777 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);778779 Ok(())780 }781782 fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {783 let current_index = <ItemListIndex>::get(item.collection)784 .checked_add(1)785 .expect("Item list index id error");786787 let item_owner = item.owner.clone();788 let collection_id = item.collection.clone();789 Self::add_token_index(collection_id, current_index, item.owner.clone())?;790791 <ItemListIndex>::insert(collection_id, current_index);792 <NftItemList<T>>::insert(collection_id, current_index, item);793794 795 let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())796 .checked_add(1)797 .unwrap();798 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);799800 Ok(())801 }802803 fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {804 ensure!(805 <ReFungibleItemList<T>>::contains_key(collection_id, item_id),806 "Item does not exists"807 );808 let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);809 let item = collection810 .owner811 .iter()812 .filter(|&i| i.owner == owner)813 .next()814 .unwrap();815 Self::remove_token_index(collection_id, item_id, owner.clone())?;816817 818 <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));819820 821 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())822 .checked_sub(item.fraction as u64)823 .unwrap();824 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);825826 <ReFungibleItemList<T>>::remove(collection_id, item_id);827828 Ok(())829 }830831 fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {832 ensure!(833 <NftItemList<T>>::contains_key(collection_id, item_id),834 "Item does not exists"835 );836 let item = <NftItemList<T>>::get(collection_id, item_id);837 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;838839 840 <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));841842 843 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())844 .checked_sub(1)845 .unwrap();846 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);847 <NftItemList<T>>::remove(collection_id, item_id);848849 Ok(())850 }851852 fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {853 ensure!(854 <FungibleItemList<T>>::contains_key(collection_id, item_id),855 "Item does not exists"856 );857 let item = <FungibleItemList<T>>::get(collection_id, item_id);858 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;859860 861 <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));862863 864 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())865 .checked_sub(item.value as u64)866 .unwrap();867 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);868869 <FungibleItemList<T>>::remove(collection_id, item_id);870871 Ok(())872 }873874 fn collection_exists(collection_id: u64) -> DispatchResult {875 ensure!(876 <Collection<T>>::contains_key(collection_id),877 "This collection does not exist"878 );879 Ok(())880 }881882 fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {883 Self::collection_exists(collection_id)?;884885 let target_collection = <Collection<T>>::get(collection_id);886 ensure!(887 subject == target_collection.owner,888 "You do not own this collection"889 );890891 Ok(())892 }893894 fn is_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> bool {895896 let target_collection = <Collection<T>>::get(collection_id);897 let mut result: bool = subject == target_collection.owner;898 let exists = <AdminList<T>>::contains_key(collection_id);899900 if !result & exists {901 if <AdminList<T>>::get(collection_id).contains(&subject) {902 result = true903 }904 }905906 result907 }908909 fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {910 911 Self::collection_exists(collection_id)?;912 let result = Self::is_owner_or_admin_permissions(collection_id, subject.clone());913914 ensure!(result, "You do not have permissions to modify this collection");915 Ok(())916 }917918 fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool {919 let target_collection = <Collection<T>>::get(collection_id);920921 match target_collection.mode {922 CollectionMode::NFT(_) => {923 <NftItemList<T>>::get(collection_id, item_id).owner == subject924 }925 CollectionMode::Fungible(_) => {926 <FungibleItemList<T>>::get(collection_id, item_id).owner == subject927 }928 CollectionMode::ReFungible(_, _) => {929 <ReFungibleItemList<T>>::get(collection_id, item_id)930 .owner931 .iter()932 .any(|i| i.owner == subject)933 }934 CollectionMode::Invalid => false,935 }936 }937938 fn check_white_list(collection_id: u64, address: T::AccountId) -> DispatchResult {939940 let mes = "Address is not in white list";941 ensure!(<WhiteList<T>>::contains_key(collection_id), mes);942 let wl = <WhiteList<T>>::get(collection_id);943 ensure!(wl.contains(&address.clone()), mes);944945 Ok(())946 }947948 fn transfer_fungible(949 collection_id: u64,950 item_id: u64,951 value: u64,952 owner: T::AccountId,953 new_owner: T::AccountId,954 ) -> DispatchResult {955956 ensure!(957 <FungibleItemList<T>>::contains_key(collection_id, item_id),958 "Item not exists"959 );960961 let full_item = <FungibleItemList<T>>::get(collection_id, item_id);962 let amount = full_item.value;963964 ensure!(amount >= value.into(), "Item balance not enouth");965966 967 let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone())968 .checked_sub(value)969 .unwrap();970 <Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);971972 let mut new_owner_account_id = 0;973 let new_owner_items = <AddressTokens<T>>::get(collection_id, new_owner.clone());974 if new_owner_items.len() > 0 {975 new_owner_account_id = new_owner_items[0];976 }977978 let val64 = value.into();979980 981 if amount == val64 && new_owner_account_id == 0 {982 983 984 let mut new_full_item = full_item.clone();985 new_full_item.owner = new_owner.clone();986 <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);987988 989 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())990 .checked_add(value)991 .unwrap();992 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);993994 995 Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;996 } else {997 let mut new_full_item = full_item.clone();998 new_full_item.value -= val64;9991000 1001 if new_owner_account_id > 0 {1002 1003 let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);1004 item.value += val64;10051006 1007 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1008 .checked_add(value)1009 .unwrap();1010 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);10111012 <FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);1013 } else {1014 1015 let item = FungibleItemType {1016 collection: collection_id,1017 owner: new_owner.clone(),1018 value: val64,1019 };10201021 Self::add_fungible_item(item)?;1022 }10231024 if amount == val64 {1025 Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;10261027 1028 <ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));1029 <FungibleItemList<T>>::remove(collection_id, item_id);1030 }10311032 <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);1033 }10341035 Ok(())1036 }10371038 fn transfer_refungible(1039 collection_id: u64,1040 item_id: u64,1041 value: u64,1042 owner: T::AccountId,1043 new_owner: T::AccountId,1044 ) -> DispatchResult {10451046 ensure!(1047 <ReFungibleItemList<T>>::contains_key(collection_id, item_id),1048 "Item not exists"1049 );10501051 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);1052 let item = full_item1053 .owner1054 .iter()1055 .filter(|i| i.owner == owner)1056 .next()1057 .unwrap();1058 let amount = item.fraction;10591060 ensure!(amount >= value.into(), "Item balance not enouth");10611062 1063 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1064 .checked_sub(value)1065 .unwrap();1066 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);10671068 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1069 .checked_add(value)1070 .unwrap();1071 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);10721073 let old_owner = item.owner.clone();1074 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);1075 let val64 = value.into();10761077 1078 if amount == val64 && !new_owner_has_account {1079 1080 1081 let mut new_full_item = full_item.clone();1082 new_full_item1083 .owner1084 .iter_mut()1085 .find(|i| i.owner == owner)1086 .unwrap()1087 .owner = new_owner.clone();1088 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);10891090 1091 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;1092 } else {1093 let mut new_full_item = full_item.clone();1094 new_full_item1095 .owner1096 .iter_mut()1097 .find(|i| i.owner == owner)1098 .unwrap()1099 .fraction -= val64;11001101 1102 if new_owner_has_account {1103 1104 new_full_item1105 .owner1106 .iter_mut()1107 .find(|i| i.owner == new_owner)1108 .unwrap()1109 .fraction += val64;1110 } else {1111 1112 new_full_item.owner.push(Ownership {1113 owner: new_owner.clone(),1114 fraction: val64,1115 });1116 Self::add_token_index(collection_id, item_id, new_owner.clone())?;1117 }11181119 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);1120 }11211122 Ok(())1123 }11241125 fn transfer_nft(1126 collection_id: u64,1127 item_id: u64,1128 sender: T::AccountId,1129 new_owner: T::AccountId,1130 ) -> DispatchResult {1131 1132 ensure!(1133 <NftItemList<T>>::contains_key(collection_id, item_id),1134 "Item not exists"1135 );11361137 let mut item = <NftItemList<T>>::get(collection_id, item_id);11381139 ensure!(1140 sender == item.owner,1141 "sender parameter and item owner must be equal"1142 );11431144 1145 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1146 .checked_sub(1)1147 .unwrap();1148 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);11491150 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1151 .checked_add(1)1152 .unwrap();1153 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);11541155 1156 let old_owner = item.owner.clone();1157 item.owner = new_owner.clone();1158 <NftItemList<T>>::insert(collection_id, item_id, item);11591160 1161 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;11621163 1164 <ApprovedList<T>>::remove(collection_id, (item_id, old_owner));1165 Ok(())1166 }11671168 fn init_collection(item: &CollectionType<T::AccountId>){11691170 1171 assert!(item.decimal_points <= 4, "decimal_points parameter must be lower than 4");1172 assert!(item.name.len() <= 64, "Collection name can not be longer than 63 char");1173 assert!(item.name.len() <= 256, "Collection description can not be longer than 255 char");1174 assert!(item.token_prefix.len() <= 16, "Token prefix can not be longer than 15 char");1175 1176 1177 let next_id = CreatedCollectionCount::get()1178 .checked_add(1)1179 .expect("collection id error");1180 1181 CreatedCollectionCount::put(next_id); 1182 }11831184 fn init_nft_token(item: &NftItemType<T::AccountId>){11851186 let current_index = <ItemListIndex>::get(item.collection)1187 .checked_add(1)1188 .expect("Item list index id error");11891190 let item_owner = item.owner.clone();1191 let collection_id = item.collection.clone();1192 Self::add_token_index(collection_id, current_index, item.owner.clone()).unwrap();11931194 <ItemListIndex>::insert(collection_id, current_index);11951196 1197 let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())1198 .checked_add(1)1199 .unwrap();1200 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);1201 }12021203 fn init_fungible_token(item: &FungibleItemType<T::AccountId>){12041205 let current_index = <ItemListIndex>::get(item.collection)1206 .checked_add(1)1207 .expect("Item list index id error");1208 let owner = item.owner.clone();1209 let value = item.value as u64;12101211 Self::add_token_index(item.collection, current_index, owner.clone()).unwrap();12121213 <ItemListIndex>::insert(item.collection, current_index);12141215 1216 let new_balance = <Balance<T>>::get(item.collection, owner.clone())1217 .checked_add(value)1218 .unwrap();1219 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);1220 }12211222 fn init_refungible_token(item: &ReFungibleItemType<T::AccountId>){12231224 let current_index = <ItemListIndex>::get(item.collection)1225 .checked_add(1)1226 .expect("Item list index id error");12271228 let value = item.owner.first().unwrap().fraction as u64;1229 let owner = item.owner.first().unwrap().owner.clone();12301231 Self::add_token_index(item.collection, current_index, owner.clone()).unwrap();12321233 <ItemListIndex>::insert(item.collection, current_index);12341235 1236 let new_balance = <Balance<T>>::get(item.collection, owner.clone())1237 .checked_add(value)1238 .unwrap();1239 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);1240 }12411242 fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {1243 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1244 if list_exists {1245 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1246 let item_contains = list.contains(&item_index.clone());12471248 if !item_contains {1249 list.push(item_index.clone());1250 }12511252 <AddressTokens<T>>::insert(collection_id, owner.clone(), list);1253 } else {1254 let mut itm = Vec::new();1255 itm.push(item_index.clone());1256 <AddressTokens<T>>::insert(collection_id, owner, itm);1257 }12581259 Ok(())1260 }12611262 fn remove_token_index(1263 collection_id: u64,1264 item_index: u64,1265 owner: T::AccountId,1266 ) -> DispatchResult {1267 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1268 if list_exists {1269 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1270 let item_contains = list.contains(&item_index.clone());12711272 if item_contains {1273 list.retain(|&item| item != item_index);1274 <AddressTokens<T>>::insert(collection_id, owner, list);1275 }1276 }12771278 Ok(())1279 }12801281 fn move_token_index(1282 collection_id: u64,1283 item_index: u64,1284 old_owner: T::AccountId,1285 new_owner: T::AccountId,1286 ) -> DispatchResult {1287 Self::remove_token_index(collection_id, item_index, old_owner)?;1288 Self::add_token_index(collection_id, item_index, new_owner)?;12891290 Ok(())1291 }1292}1293129412951296129712981299pub type Multiplier = FixedU128;13001301type BalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1302 <T as system::Trait>::AccountId,1303>>::Balance;1304type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1305 <T as system::Trait>::AccountId,1306>>::NegativeImbalance;1307130813091310#[derive(Encode, Decode, Clone, Eq, PartialEq)]1311pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(1312 #[codec(compact)] BalanceOf<T>,1313);13141315impl<T: Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug1316 for ChargeTransactionPayment<T>1317{1318 #[cfg(feature = "std")]1319 fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1320 write!(f, "ChargeTransactionPayment<{:?}>", self.0)1321 }1322 #[cfg(not(feature = "std"))]1323 fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1324 Ok(())1325 }1326}13271328impl<T: Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T>1329where1330 T::Call:1331 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1332 BalanceOf<T>: Send + Sync + FixedPointOperand,1333{1334 1335 pub fn from(fee: BalanceOf<T>) -> Self {1336 Self(fee)1337 }13381339 pub fn traditional_fee(1340 len: usize,1341 info: &DispatchInfoOf<T::Call>,1342 tip: BalanceOf<T>,1343 ) -> BalanceOf<T>1344 where1345 T::Call: Dispatchable<Info = DispatchInfo>,1346 {1347 <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)1348 }13491350 fn withdraw_fee(1351 &self,1352 who: &T::AccountId,1353 call: &T::Call,1354 info: &DispatchInfoOf<T::Call>,1355 len: usize,1356 ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {1357 let tip = self.0;13581359 1360 1361 let fee = match call.is_sub_type() {1362 Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1363 _ => Self::traditional_fee(len, info, tip), 1364 1365 };13661367 1368 1369 let sponsor: T::AccountId = match call.is_sub_type() {1370 Some(Call::create_item(collection_id, _properties, _owner)) => {1371 <Collection<T>>::get(collection_id).sponsor1372 }1373 Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {1374 <Collection<T>>::get(collection_id).sponsor1375 }13761377 _ => T::AccountId::default(),1378 };13791380 let mut who_pays_fee: T::AccountId = sponsor.clone();1381 if sponsor == T::AccountId::default() {1382 who_pays_fee = who.clone();1383 }13841385 1386 if fee.is_zero() {1387 return Ok((fee, None));1388 }13891390 match <T as transaction_payment::Trait>::Currency::withdraw(1391 &who_pays_fee,1392 fee,1393 if tip.is_zero() {1394 WithdrawReason::TransactionPayment.into()1395 } else {1396 WithdrawReason::TransactionPayment | WithdrawReason::Tip1397 },1398 ExistenceRequirement::KeepAlive,1399 ) {1400 Ok(imbalance) => Ok((fee, Some(imbalance))),1401 Err(_) => Err(InvalidTransaction::Payment.into()),1402 }1403 }1404}14051406impl<T: Trait + transaction_payment::Trait + Send + Sync> SignedExtension1407 for ChargeTransactionPayment<T>1408where1409 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,1410 T::Call:1411 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1412{1413 const IDENTIFIER: &'static str = "ChargeTransactionPayment";1414 type AccountId = T::AccountId;1415 type Call = T::Call;1416 type AdditionalSigned = ();1417 type Pre = (1418 BalanceOf<T>,1419 Self::AccountId,1420 Option<NegativeImbalanceOf<T>>,1421 BalanceOf<T>,1422 );1423 fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {1424 Ok(())1425 }14261427 fn validate(1428 &self,1429 who: &Self::AccountId,1430 call: &Self::Call,1431 info: &DispatchInfoOf<Self::Call>,1432 len: usize,1433 ) -> TransactionValidity {1434 let (fee, _) = self.withdraw_fee(who, call, info, len)?;14351436 let mut r = ValidTransaction::default();1437 1438 1439 r.priority = fee.saturated_into::<TransactionPriority>();1440 Ok(r)1441 }14421443 fn pre_dispatch(1444 self,1445 who: &Self::AccountId,1446 call: &Self::Call,1447 info: &DispatchInfoOf<Self::Call>,1448 len: usize,1449 ) -> Result<Self::Pre, TransactionValidityError> {1450 let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;1451 Ok((self.0, who.clone(), imbalance, fee))1452 }14531454 fn post_dispatch(1455 pre: Self::Pre,1456 info: &DispatchInfoOf<Self::Call>,1457 post_info: &PostDispatchInfoOf<Self::Call>,1458 len: usize,1459 _result: &DispatchResult,1460 ) -> Result<(), TransactionValidityError> {1461 let (tip, who, imbalance, fee) = pre;1462 if let Some(payed) = imbalance {1463 let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(1464 len as u32, info, post_info, tip,1465 );1466 let refund = fee.saturating_sub(actual_fee);1467 let actual_payment =1468 match <T as transaction_payment::Trait>::Currency::deposit_into_existing(1469 &who, refund,1470 ) {1471 Ok(refund_imbalance) => {1472 1473 1474 match payed.offset(refund_imbalance) {1475 Ok(actual_payment) => actual_payment,1476 Err(_) => return Err(InvalidTransaction::Payment.into()),1477 }1478 }1479 1480 1481 Err(_) => payed,1482 };1483 let imbalances = actual_payment.split(tip);1484 <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(1485 Some(imbalances.0).into_iter().chain(Some(imbalances.1)),1486 );1487 }1488 Ok(())1489 }1490}1491