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,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, fraction: value});547548 let item = ReFungibleItemType {549 collection: collection_id,550 owner: owner_list,551 data: properties552 };553554 Self::add_refungible_item(item)?;555 },556 _ => ()557 };558559 560 Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));561562 Ok(())563 }564565 #[weight = 0]566 pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {567568 let sender = ensure_signed(origin)?;569 Self::collection_exists(collection_id)?;570571 572 let target_collection = <Collection<T>>::get(collection_id);573 ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) || 574 Self::is_owner_or_admin_permissions(collection_id, sender.clone()), 575 "Only item owner, collection owner and admins can modify item");576577 if target_collection.access == AccessMode::WhiteList {578 Self::check_white_list(collection_id, sender.clone())?;579 }580581 match target_collection.mode582 {583 CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,584 CollectionMode::Fungible(_) => Self::burn_fungible_item(collection_id, item_id)?,585 CollectionMode::ReFungible(_, _) => Self::burn_refungible_item(collection_id, item_id, sender.clone())?,586 _ => ()587 };588589 590 Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));591592 Ok(())593 }594595 #[weight = 0]596 pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {597598 let sender = ensure_signed(origin)?;599600 601 let target_collection = <Collection<T>>::get(collection_id);602 ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) || 603 Self::is_owner_or_admin_permissions(collection_id, sender.clone()), 604 "Only item owner, collection owner and admins can modify item");605606 if target_collection.access == AccessMode::WhiteList {607 Self::check_white_list(collection_id, sender.clone())?;608 Self::check_white_list(collection_id, recipient.clone())?;609 }610611 match target_collection.mode612 {613 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,614 CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,615 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, sender.clone(), recipient)?,616 _ => ()617 };618619 Ok(())620 }621622 #[weight = 0]623 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {624625 let sender = ensure_signed(origin)?;626627 628 let target_collection = <Collection<T>>::get(collection_id);629 ensure!(Self::is_item_owner(sender.clone(), collection_id, item_id) || 630 Self::is_owner_or_admin_permissions(collection_id, sender.clone()), 631 "Only item owner, collection owner and admins can approve");632633 if target_collection.access == AccessMode::WhiteList {634 Self::check_white_list(collection_id, sender.clone())?;635 Self::check_white_list(collection_id, approved.clone())?;636 }637638 639 let amount = 100000000;640641 let list_exists = <ApprovedList<T>>::contains_key(collection_id, (item_id, sender.clone()));642 if list_exists {643644 let mut list = <ApprovedList<T>>::get(collection_id, (item_id, sender.clone()));645 let item_contains = list.iter().any(|i| i.approved == approved);646647 if !item_contains {648 list.push(ApprovePermissions { approved: approved.clone(), amount: amount });649 <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);650 }651 } else {652653 let mut list = Vec::new();654 list.push(ApprovePermissions { approved: approved.clone(), amount: amount });655 <ApprovedList<T>>::insert(collection_id, (item_id, sender.clone()), list);656 }657658 Ok(())659 }660661 #[weight = 0]662 pub fn transfer_from(origin, from: T::AccountId, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64 ) -> DispatchResult {663664 let sender = ensure_signed(origin)?;665 let mut appoved_transfer = false;666667 668 if <ApprovedList<T>>::contains_key(collection_id, (item_id, from.clone())) {669 let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));670 let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());671 appoved_transfer = opt_item.is_some();672 ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved");673 }674675 676 let target_collection = <Collection<T>>::get(collection_id);677 ensure!(appoved_transfer || Self::is_owner_or_admin_permissions(collection_id, sender.clone()), 678 "Only item owner, collection owner and admins can modify items");679680 if target_collection.access == AccessMode::WhiteList {681 Self::check_white_list(collection_id, sender.clone())?;682 Self::check_white_list(collection_id, recipient.clone())?;683 }684685 686 let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))687 .into_iter().filter(|i| i.approved != sender.clone()).collect();688 <ApprovedList<T>>::insert(collection_id, (item_id, from.clone()), approve_list);689690691 match target_collection.mode692 {693 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, from, recipient)?,694 CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, item_id, value, from.clone(), recipient)?,695 CollectionMode::ReFungible(_, _) => Self::transfer_refungible(collection_id, item_id, value, from.clone(), recipient)?,696 _ => ()697 };698699 Ok(())700 }701702 #[weight = 0]703 pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {704705 706 707 708 709710 711712 713714 Ok(())715 }716717 #[weight = 0]718 pub fn set_offchain_schema(719 origin,720 collection_id: u64,721 schema: Vec<u8>722 ) -> DispatchResult {723 let sender = ensure_signed(origin)?;724 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;725726 let mut target_collection = <Collection<T>>::get(collection_id);727 target_collection.offchain_schema = schema;728 <Collection<T>>::insert(collection_id, target_collection);729730 Ok(())731 }732 }733}734735impl<T: Trait> Module<T> {736 fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {737 let current_index = <ItemListIndex>::get(item.collection)738 .checked_add(1)739 .expect("Item list index id error");740 let itemcopy = item.clone();741 let owner = item.owner.clone();742 let value = item.value as u64;743744 Self::add_token_index(item.collection, current_index, owner.clone())?;745746 <ItemListIndex>::insert(item.collection, current_index);747 <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);748749 750 let new_balance = <Balance<T>>::get(item.collection, owner.clone())751 .checked_add(value)752 .unwrap();753 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);754755 Ok(())756 }757758 fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {759 let current_index = <ItemListIndex>::get(item.collection)760 .checked_add(1)761 .expect("Item list index id error");762 let itemcopy = item.clone();763764 let value = item.owner.first().unwrap().fraction as u64;765 let owner = item.owner.first().unwrap().owner.clone();766767 Self::add_token_index(item.collection, current_index, owner.clone())?;768769 <ItemListIndex>::insert(item.collection, current_index);770 <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);771772 773 let new_balance = <Balance<T>>::get(item.collection, owner.clone())774 .checked_add(value)775 .unwrap();776 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);777778 Ok(())779 }780781 fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {782 let current_index = <ItemListIndex>::get(item.collection)783 .checked_add(1)784 .expect("Item list index id error");785786 let item_owner = item.owner.clone();787 let collection_id = item.collection.clone();788 Self::add_token_index(collection_id, current_index, item.owner.clone())?;789790 <ItemListIndex>::insert(collection_id, current_index);791 <NftItemList<T>>::insert(collection_id, current_index, item);792793 794 let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())795 .checked_add(1)796 .unwrap();797 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);798799 Ok(())800 }801802 fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {803 ensure!(804 <ReFungibleItemList<T>>::contains_key(collection_id, item_id),805 "Item does not exists"806 );807 let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);808 let item = collection809 .owner810 .iter()811 .filter(|&i| i.owner == owner)812 .next()813 .unwrap();814 Self::remove_token_index(collection_id, item_id, owner.clone())?;815816 817 <ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));818819 820 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())821 .checked_sub(item.fraction as u64)822 .unwrap();823 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);824825 <ReFungibleItemList<T>>::remove(collection_id, item_id);826827 Ok(())828 }829830 fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {831 ensure!(832 <NftItemList<T>>::contains_key(collection_id, item_id),833 "Item does not exists"834 );835 let item = <NftItemList<T>>::get(collection_id, item_id);836 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;837838 839 <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));840841 842 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())843 .checked_sub(1)844 .unwrap();845 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);846 <NftItemList<T>>::remove(collection_id, item_id);847848 Ok(())849 }850851 fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {852 ensure!(853 <FungibleItemList<T>>::contains_key(collection_id, item_id),854 "Item does not exists"855 );856 let item = <FungibleItemList<T>>::get(collection_id, item_id);857 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;858859 860 <ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));861862 863 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())864 .checked_sub(item.value as u64)865 .unwrap();866 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);867868 <FungibleItemList<T>>::remove(collection_id, item_id);869870 Ok(())871 }872873 fn collection_exists(collection_id: u64) -> DispatchResult {874 ensure!(875 <Collection<T>>::contains_key(collection_id),876 "This collection does not exist"877 );878 Ok(())879 }880881 fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {882 Self::collection_exists(collection_id)?;883884 let target_collection = <Collection<T>>::get(collection_id);885 ensure!(886 subject == target_collection.owner,887 "You do not own this collection"888 );889890 Ok(())891 }892893 fn is_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> bool {894895 let target_collection = <Collection<T>>::get(collection_id);896 let mut result: bool = subject == target_collection.owner;897 let exists = <AdminList<T>>::contains_key(collection_id);898899 if !result & exists {900 if <AdminList<T>>::get(collection_id).contains(&subject) {901 result = true902 }903 }904905 result906 }907908 fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {909 910 Self::collection_exists(collection_id)?;911 let result = Self::is_owner_or_admin_permissions(collection_id, subject.clone());912913 ensure!(result, "You do not have permissions to modify this collection");914 Ok(())915 }916917 fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool {918 let target_collection = <Collection<T>>::get(collection_id);919920 match target_collection.mode {921 CollectionMode::NFT(_) => {922 <NftItemList<T>>::get(collection_id, item_id).owner == subject923 }924 CollectionMode::Fungible(_) => {925 <FungibleItemList<T>>::get(collection_id, item_id).owner == subject926 }927 CollectionMode::ReFungible(_, _) => {928 <ReFungibleItemList<T>>::get(collection_id, item_id)929 .owner930 .iter()931 .any(|i| i.owner == subject)932 }933 CollectionMode::Invalid => false,934 }935 }936937 fn check_white_list(collection_id: u64, address: T::AccountId) -> DispatchResult {938939 let mes = "Address is not in white list";940 ensure!(<WhiteList<T>>::contains_key(collection_id), mes);941 let wl = <WhiteList<T>>::get(collection_id);942 ensure!(wl.contains(&address.clone()), mes);943944 Ok(())945 }946947 fn transfer_fungible(948 collection_id: u64,949 item_id: u64,950 value: u64,951 owner: T::AccountId,952 new_owner: T::AccountId,953 ) -> DispatchResult {954955 ensure!(956 <FungibleItemList<T>>::contains_key(collection_id, item_id),957 "Item not exists"958 );959960 let full_item = <FungibleItemList<T>>::get(collection_id, item_id);961 let amount = full_item.value;962963 ensure!(amount >= value.into(), "Item balance not enouth");964965 966 let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone())967 .checked_sub(value)968 .unwrap();969 <Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);970971 let mut new_owner_account_id = 0;972 let new_owner_items = <AddressTokens<T>>::get(collection_id, new_owner.clone());973 if new_owner_items.len() > 0 {974 new_owner_account_id = new_owner_items[0];975 }976977 let val64 = value.into();978979 980 if amount == val64 && new_owner_account_id == 0 {981 982 983 let mut new_full_item = full_item.clone();984 new_full_item.owner = new_owner.clone();985 <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);986987 988 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())989 .checked_add(value)990 .unwrap();991 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);992993 994 Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;995 } else {996 let mut new_full_item = full_item.clone();997 new_full_item.value -= val64;998999 1000 if new_owner_account_id > 0 {1001 1002 let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);1003 item.value += val64;10041005 1006 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1007 .checked_add(value)1008 .unwrap();1009 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);10101011 <FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);1012 } else {1013 1014 let item = FungibleItemType {1015 collection: collection_id,1016 owner: new_owner.clone(),1017 value: val64,1018 };10191020 Self::add_fungible_item(item)?;1021 }10221023 if amount == val64 {1024 Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;10251026 1027 <ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));1028 <FungibleItemList<T>>::remove(collection_id, item_id);1029 }10301031 <FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);1032 }10331034 Ok(())1035 }10361037 fn transfer_refungible(1038 collection_id: u64,1039 item_id: u64,1040 value: u64,1041 owner: T::AccountId,1042 new_owner: T::AccountId,1043 ) -> DispatchResult {10441045 ensure!(1046 <ReFungibleItemList<T>>::contains_key(collection_id, item_id),1047 "Item not exists"1048 );10491050 let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);1051 let item = full_item1052 .owner1053 .iter()1054 .filter(|i| i.owner == owner)1055 .next()1056 .unwrap();1057 let amount = item.fraction;10581059 ensure!(amount >= value.into(), "Item balance not enouth");10601061 1062 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1063 .checked_sub(value)1064 .unwrap();1065 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);10661067 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1068 .checked_add(value)1069 .unwrap();1070 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);10711072 let old_owner = item.owner.clone();1073 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);1074 let val64 = value.into();10751076 1077 if amount == val64 && !new_owner_has_account {1078 1079 1080 let mut new_full_item = full_item.clone();1081 new_full_item1082 .owner1083 .iter_mut()1084 .find(|i| i.owner == owner)1085 .unwrap()1086 .owner = new_owner.clone();1087 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);10881089 1090 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;1091 } else {1092 let mut new_full_item = full_item.clone();1093 new_full_item1094 .owner1095 .iter_mut()1096 .find(|i| i.owner == owner)1097 .unwrap()1098 .fraction -= val64;10991100 1101 if new_owner_has_account {1102 1103 new_full_item1104 .owner1105 .iter_mut()1106 .find(|i| i.owner == new_owner)1107 .unwrap()1108 .fraction += val64;1109 } else {1110 1111 new_full_item.owner.push(Ownership {1112 owner: new_owner.clone(),1113 fraction: val64,1114 });1115 Self::add_token_index(collection_id, item_id, new_owner.clone())?;1116 }11171118 <ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);1119 }11201121 Ok(())1122 }11231124 fn transfer_nft(1125 collection_id: u64,1126 item_id: u64,1127 sender: T::AccountId,1128 new_owner: T::AccountId,1129 ) -> DispatchResult {1130 1131 ensure!(1132 <NftItemList<T>>::contains_key(collection_id, item_id),1133 "Item not exists"1134 );11351136 let mut item = <NftItemList<T>>::get(collection_id, item_id);11371138 ensure!(1139 sender == item.owner,1140 "sender parameter and item owner must be equal"1141 );11421143 1144 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())1145 .checked_sub(1)1146 .unwrap();1147 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);11481149 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())1150 .checked_add(1)1151 .unwrap();1152 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);11531154 1155 let old_owner = item.owner.clone();1156 item.owner = new_owner.clone();1157 <NftItemList<T>>::insert(collection_id, item_id, item);11581159 1160 Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;11611162 1163 <ApprovedList<T>>::remove(collection_id, (item_id, old_owner));1164 Ok(())1165 }11661167 fn init_collection(item: &CollectionType<T::AccountId>){11681169 1170 assert!(item.decimal_points <= 4, "decimal_points parameter must be lower than 4");1171 assert!(item.name.len() <= 64, "Collection name can not be longer than 63 char");1172 assert!(item.name.len() <= 256, "Collection description can not be longer than 255 char");1173 assert!(item.token_prefix.len() <= 16, "Token prefix can not be longer than 15 char");1174 1175 1176 let next_id = CreatedCollectionCount::get()1177 .checked_add(1)1178 .expect("collection id error");1179 1180 CreatedCollectionCount::put(next_id); 1181 }11821183 fn init_nft_token(item: &NftItemType<T::AccountId>){11841185 let current_index = <ItemListIndex>::get(item.collection)1186 .checked_add(1)1187 .expect("Item list index id error");11881189 let item_owner = item.owner.clone();1190 let collection_id = item.collection.clone();1191 Self::add_token_index(collection_id, current_index, item.owner.clone()).unwrap();11921193 <ItemListIndex>::insert(collection_id, current_index);11941195 1196 let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())1197 .checked_add(1)1198 .unwrap();1199 <Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);1200 }12011202 fn init_fungible_token(item: &FungibleItemType<T::AccountId>){12031204 let current_index = <ItemListIndex>::get(item.collection)1205 .checked_add(1)1206 .expect("Item list index id error");1207 let owner = item.owner.clone();1208 let value = item.value as u64;12091210 Self::add_token_index(item.collection, current_index, owner.clone()).unwrap();12111212 <ItemListIndex>::insert(item.collection, current_index);12131214 1215 let new_balance = <Balance<T>>::get(item.collection, owner.clone())1216 .checked_add(value)1217 .unwrap();1218 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);1219 }12201221 fn init_refungible_token(item: &ReFungibleItemType<T::AccountId>){12221223 let current_index = <ItemListIndex>::get(item.collection)1224 .checked_add(1)1225 .expect("Item list index id error");12261227 let value = item.owner.first().unwrap().fraction as u64;1228 let owner = item.owner.first().unwrap().owner.clone();12291230 Self::add_token_index(item.collection, current_index, owner.clone()).unwrap();12311232 <ItemListIndex>::insert(item.collection, current_index);12331234 1235 let new_balance = <Balance<T>>::get(item.collection, owner.clone())1236 .checked_add(value)1237 .unwrap();1238 <Balance<T>>::insert(item.collection, owner.clone(), new_balance);1239 }12401241 fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {1242 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1243 if list_exists {1244 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1245 let item_contains = list.contains(&item_index.clone());12461247 if !item_contains {1248 list.push(item_index.clone());1249 }12501251 <AddressTokens<T>>::insert(collection_id, owner.clone(), list);1252 } else {1253 let mut itm = Vec::new();1254 itm.push(item_index.clone());1255 <AddressTokens<T>>::insert(collection_id, owner, itm);1256 }12571258 Ok(())1259 }12601261 fn remove_token_index(1262 collection_id: u64,1263 item_index: u64,1264 owner: T::AccountId,1265 ) -> DispatchResult {1266 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());1267 if list_exists {1268 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());1269 let item_contains = list.contains(&item_index.clone());12701271 if item_contains {1272 list.retain(|&item| item != item_index);1273 <AddressTokens<T>>::insert(collection_id, owner, list);1274 }1275 }12761277 Ok(())1278 }12791280 fn move_token_index(1281 collection_id: u64,1282 item_index: u64,1283 old_owner: T::AccountId,1284 new_owner: T::AccountId,1285 ) -> DispatchResult {1286 Self::remove_token_index(collection_id, item_index, old_owner)?;1287 Self::add_token_index(collection_id, item_index, new_owner)?;12881289 Ok(())1290 }1291}1292129312941295129612971298pub type Multiplier = FixedU128;12991300type BalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1301 <T as system::Trait>::AccountId,1302>>::Balance;1303type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<1304 <T as system::Trait>::AccountId,1305>>::NegativeImbalance;1306130713081309#[derive(Encode, Decode, Clone, Eq, PartialEq)]1310pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(1311 #[codec(compact)] BalanceOf<T>,1312);13131314impl<T: Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug1315 for ChargeTransactionPayment<T>1316{1317 #[cfg(feature = "std")]1318 fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1319 write!(f, "ChargeTransactionPayment<{:?}>", self.0)1320 }1321 #[cfg(not(feature = "std"))]1322 fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {1323 Ok(())1324 }1325}13261327impl<T: Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T>1328where1329 T::Call:1330 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1331 BalanceOf<T>: Send + Sync + FixedPointOperand,1332{1333 1334 pub fn from(fee: BalanceOf<T>) -> Self {1335 Self(fee)1336 }13371338 pub fn traditional_fee(1339 len: usize,1340 info: &DispatchInfoOf<T::Call>,1341 tip: BalanceOf<T>,1342 ) -> BalanceOf<T>1343 where1344 T::Call: Dispatchable<Info = DispatchInfo>,1345 {1346 <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)1347 }13481349 fn withdraw_fee(1350 &self,1351 who: &T::AccountId,1352 call: &T::Call,1353 info: &DispatchInfoOf<T::Call>,1354 len: usize,1355 ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {1356 let tip = self.0;13571358 1359 1360 let fee = match call.is_sub_type() {1361 Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),1362 _ => Self::traditional_fee(len, info, tip), 1363 1364 };13651366 1367 1368 let sponsor: T::AccountId = match call.is_sub_type() {1369 Some(Call::create_item(collection_id, _properties, _owner)) => {1370 <Collection<T>>::get(collection_id).sponsor1371 }1372 Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {1373 <Collection<T>>::get(collection_id).sponsor1374 }13751376 _ => T::AccountId::default(),1377 };13781379 let mut who_pays_fee: T::AccountId = sponsor.clone();1380 if sponsor == T::AccountId::default() {1381 who_pays_fee = who.clone();1382 }13831384 1385 if fee.is_zero() {1386 return Ok((fee, None));1387 }13881389 match <T as transaction_payment::Trait>::Currency::withdraw(1390 &who_pays_fee,1391 fee,1392 if tip.is_zero() {1393 WithdrawReason::TransactionPayment.into()1394 } else {1395 WithdrawReason::TransactionPayment | WithdrawReason::Tip1396 },1397 ExistenceRequirement::KeepAlive,1398 ) {1399 Ok(imbalance) => Ok((fee, Some(imbalance))),1400 Err(_) => Err(InvalidTransaction::Payment.into()),1401 }1402 }1403}14041405impl<T: Trait + transaction_payment::Trait + Send + Sync> SignedExtension1406 for ChargeTransactionPayment<T>1407where1408 BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,1409 T::Call:1410 Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,1411{1412 const IDENTIFIER: &'static str = "ChargeTransactionPayment";1413 type AccountId = T::AccountId;1414 type Call = T::Call;1415 type AdditionalSigned = ();1416 type Pre = (1417 BalanceOf<T>,1418 Self::AccountId,1419 Option<NegativeImbalanceOf<T>>,1420 BalanceOf<T>,1421 );1422 fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {1423 Ok(())1424 }14251426 fn validate(1427 &self,1428 who: &Self::AccountId,1429 call: &Self::Call,1430 info: &DispatchInfoOf<Self::Call>,1431 len: usize,1432 ) -> TransactionValidity {1433 let (fee, _) = self.withdraw_fee(who, call, info, len)?;14341435 let mut r = ValidTransaction::default();1436 1437 1438 r.priority = fee.saturated_into::<TransactionPriority>();1439 Ok(r)1440 }14411442 fn pre_dispatch(1443 self,1444 who: &Self::AccountId,1445 call: &Self::Call,1446 info: &DispatchInfoOf<Self::Call>,1447 len: usize,1448 ) -> Result<Self::Pre, TransactionValidityError> {1449 let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;1450 Ok((self.0, who.clone(), imbalance, fee))1451 }14521453 fn post_dispatch(1454 pre: Self::Pre,1455 info: &DispatchInfoOf<Self::Call>,1456 post_info: &PostDispatchInfoOf<Self::Call>,1457 len: usize,1458 _result: &DispatchResult,1459 ) -> Result<(), TransactionValidityError> {1460 let (tip, who, imbalance, fee) = pre;1461 if let Some(payed) = imbalance {1462 let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(1463 len as u32, info, post_info, tip,1464 );1465 let refund = fee.saturating_sub(actual_fee);1466 let actual_payment =1467 match <T as transaction_payment::Trait>::Currency::deposit_into_existing(1468 &who, refund,1469 ) {1470 Ok(refund_imbalance) => {1471 1472 1473 match payed.offset(refund_imbalance) {1474 Ok(actual_payment) => actual_payment,1475 Err(_) => return Err(InvalidTransaction::Payment.into()),1476 }1477 }1478 1479 1480 Err(_) => payed,1481 };1482 let imbalances = actual_payment.split(tip);1483 <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(1484 Some(imbalances.0).into_iter().chain(Some(imbalances.1)),1485 );1486 }1487 Ok(())1488 }1489}1490