difftreelog
Burn item owner check added
in: master
1 file changed
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.rs56use codec::{Decode, Encode};7use frame_support::{decl_event, decl_module, decl_storage, dispatch::DispatchResult, ensure};8use frame_system::{self as system, ensure_signed};9use sp_runtime::sp_std::prelude::Vec;1011#[cfg(test)]12mod mock;1314#[cfg(test)]15mod tests;1617#[derive(Encode, Decode, Debug, Clone, PartialEq)]18pub enum AccessMode {19 Normal,20 WhiteList,21}22impl Default for AccessMode { fn default() -> Self { Self::Normal } }2324#[derive(Encode, Decode, Debug, Eq, Clone, PartialEq)]25pub enum CollectionMode {26 Invalid,27 NFT,28 Fungible,29 ReFungible,30}31impl Default for CollectionMode { fn default() -> Self { Self::Invalid } }3233#[derive(Encode, Decode, Default, Clone, PartialEq)]34#[cfg_attr(feature = "std", derive(Debug))]35pub struct Ownership<AccountId> {36 pub owner: AccountId,37 pub fraction: u12838}3940#[derive(Encode, Decode, Default, Clone, PartialEq)]41#[cfg_attr(feature = "std", derive(Debug))]42pub struct CollectionType<AccountId> {43 pub owner: AccountId,44 pub mode: CollectionMode,45 pub access: AccessMode,46 pub next_item_id: u64,47 pub decimal_points: u32,48 pub name: Vec<u16>, // 64 include null escape char49 pub description: Vec<u16>, // 256 include null escape char50 pub token_prefix: Vec<u8>, // 16 include null escape char51 pub custom_data_size: u32,52}5354#[derive(Encode, Decode, Default, Clone, PartialEq)]55#[cfg_attr(feature = "std", derive(Debug))]56pub struct CollectionAdminsType<AccountId> {57 pub admin: AccountId,58 pub collection_id: u64,59}6061#[derive(Encode, Decode, Default, Clone, PartialEq)]62#[cfg_attr(feature = "std", derive(Debug))]63pub struct NftItemType<AccountId> {64 pub collection: u64,65 pub owner: AccountId,66 pub data: Vec<u8>,67}6869#[derive(Encode, Decode, Default, Clone, PartialEq)]70#[cfg_attr(feature = "std", derive(Debug))]71pub struct FungibleItemType<AccountId> {72 pub collection: u64,73 pub owner: Vec<AccountId>,74 pub data: Vec<u64>,75}7677#[derive(Encode, Decode, Default, Clone, PartialEq)]78#[cfg_attr(feature = "std", derive(Debug))]79pub struct ReFungibleItemType<AccountId> {80 pub collection: u64,81 pub owner: Vec<Ownership<AccountId>>,82}8384pub trait Trait: system::Trait {85 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;86}8788decl_storage! {89 trait Store for Module<T: Trait> as Nft {9091 // Next available collection ID92 NextCollectionID get(fn next_collection_id): u64;93 pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;94 pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;9596 // Balance owner per collection map97 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;98 pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => Vec<T::AccountId>;99100 // Item collections101 pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;102 pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;103 pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;104 ItemListIndex get(fn item_index): map hasher(blake2_128_concat) u64 => u64;105106 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;107 }108}109110decl_event!(111 pub enum Event<T>112 where113 AccountId = <T as system::Trait>::AccountId,114 {115 Created(u64, u8, AccountId),116 ItemCreated(u64, u64),117 ItemDestroyed(u64, u64),118 }119);120121decl_module! {122 pub struct Module<T: Trait> for enum Call where origin: T::Origin {123124 fn deposit_event() = default;125126 // Create collection of NFT with given parameters127 //128 // @param customDataSz size of custom data in each collection item129 // returns collection ID130 #[weight = 0]131 pub fn create_collection( origin,132 collection_name: Vec<u16>,133 collection_description: Vec<u16>,134 token_prefix: Vec<u8>,135 mode: u8,136 decimal_points: u32,137 custom_data_size: u32) -> DispatchResult {138139 // Anyone can create a collection140 let who = ensure_signed(origin)?;141 let collection_mode: CollectionMode;142 match mode {143 1 => collection_mode = CollectionMode::NFT,144 2 => collection_mode = CollectionMode::Fungible,145 3 => collection_mode = CollectionMode::ReFungible,146 _ => collection_mode = CollectionMode::Invalid147 }148149 // check type150 ensure!((collection_mode == CollectionMode::Fungible || collection_mode == CollectionMode::NFT || collection_mode == CollectionMode::ReFungible), 151 "Collection mode must be Fungible, NFT or ReFungible"); 152153 // NFT checks154 if collection_mode == CollectionMode::NFT155 {156 ensure!(decimal_points == 0, "Collection in NFT mode must have zero in decimal_points parameter"); 157 }158159 // Fungible checks160 if collection_mode == CollectionMode::Fungible161 {162 ensure!(custom_data_size == 0, "Collection in Fungible mode must have zero in custom_data_size parameter"); 163 ensure!(decimal_points != 0, "Collection in Fungible mode must have not zero in decimal_points parameter"); 164 }165166 // check params167 ensure!(decimal_points < 100, "decimal_points parameter must be lower than 100"); 168169 let mut name = collection_name.to_vec();170 name.push(0);171 ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");172173 let mut description = collection_description.to_vec();174 description.push(0);175 ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");176177 let mut prefix = token_prefix.to_vec();178 prefix.push(0);179 ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");180181 // Generate next collection ID182 let next_id = NextCollectionID::get()183 .checked_add(1)184 .expect("collection id error");185186 NextCollectionID::put(next_id);187188 // Create new collection189 let new_collection = CollectionType {190 owner: who.clone(),191 name: name,192 mode: collection_mode.clone(),193 access: AccessMode::Normal,194 description: description,195 decimal_points: decimal_points,196 token_prefix: prefix,197 next_item_id: next_id,198 custom_data_size: custom_data_size,199 };200201 // Add new collection to map202 <Collection<T>>::insert(next_id, new_collection);203204 // call event205 Self::deposit_event(RawEvent::Created(next_id, mode, who.clone()));206207 Ok(())208 }209210 #[weight = 0]211 pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {212213 let sender = ensure_signed(origin)?;214 Self::check_owner_permissions(collection_id, sender)?;215216 <AddressTokens<T>>::remove_prefix(collection_id);217 <ApprovedList<T>>::remove_prefix(collection_id);218 <Balance<T>>::remove_prefix(collection_id);219 <ItemListIndex>::remove(collection_id);220 <AdminList<T>>::remove(collection_id);221 <Collection<T>>::remove(collection_id);222223 Ok(())224 }225226 #[weight = 0]227 pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {228229 let sender = ensure_signed(origin)?;230 Self::check_owner_permissions(collection_id, sender)?;231 let mut target_collection = <Collection<T>>::get(collection_id);232 target_collection.owner = new_owner;233 <Collection<T>>::insert(collection_id, target_collection);234235 Ok(())236 }237238 #[weight = 0]239 pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {240241 let sender = ensure_signed(origin)?;242 Self::check_owner_or_admin_permissions(collection_id, sender)?;243 let mut admin_arr: Vec<T::AccountId> = Vec::new();244245 if <AdminList<T>>::contains_key(collection_id)246 {247 admin_arr = <AdminList<T>>::get(collection_id);248 ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");249 }250251 admin_arr.push(new_admin_id);252 <AdminList<T>>::insert(collection_id, admin_arr);253254 Ok(())255 }256257 #[weight = 0]258 pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {259260 let sender = ensure_signed(origin)?;261 Self::check_owner_or_admin_permissions(collection_id, sender)?;262263 if <AdminList<T>>::contains_key(collection_id)264 {265 let mut admin_arr = <AdminList<T>>::get(collection_id);266 admin_arr.retain(|i| *i != account_id);267 <AdminList<T>>::insert(collection_id, admin_arr);268 }269270 Ok(())271 }272273 #[weight = 0]274 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {275276 let sender = ensure_signed(origin)?;277278 // check size279 let target_collection = <Collection<T>>::get(collection_id);280 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");281282 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;283284 let new_balance = <Balance<T>>::get(collection_id, owner.clone()) + 1;285 <Balance<T>>::insert(collection_id, owner.clone(), new_balance);286287 // TODO: implement other modes288 ensure!(target_collection.mode == CollectionMode::NFT, "Collection type not implemented");289290 if target_collection.mode == CollectionMode::NFT291 {292 // Create nft item293 let item = NftItemType {294 collection: collection_id,295 owner: owner,296 data: properties,297 };298299 Self::add_nft_item(item)?;300 }301302 // call event303 Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));304305 Ok(())306 }307308 #[weight = 0]309 pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {310311 let sender = ensure_signed(origin)?;312 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;313 Self::burn_nft_item(collection_id, item_id)?;314315 // call event316 Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));317318 Ok(())319 }320321 #[weight = 0]322 pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {323324 let sender = ensure_signed(origin)?;325 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);326 if !item_owner327 {328 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;329 }330331 let target_collection = <Collection<T>>::get(collection_id);332333 // TODO: implement other modes334 ensure!(target_collection.mode == CollectionMode::NFT, "Collection type not implemented");335336 if target_collection.mode == CollectionMode::NFT337 {338 Self::transfer_nft(collection_id, item_id, recipient)?;339 }340341 Ok(())342 }343344 #[weight = 0]345 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {346347 let sender = ensure_signed(origin)?;348349 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);350 if !item_owner351 {352 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;353 }354355 let list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);356 if list_exists {357358 let mut list = <ApprovedList<T>>::get(collection_id, item_id);359 let item_contains = list.contains(&approved.clone());360361 if !item_contains {362 list.push(approved.clone());363 }364 } else {365366 let mut itm = Vec::new();367 itm.push(approved.clone());368 <ApprovedList<T>>::insert(collection_id, item_id, itm);369 }370371 Ok(())372 }373374 #[weight = 0]375 pub fn transfer_from(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, ) -> DispatchResult {376377 let mut approved: bool = false; 378 let sender = ensure_signed(origin)?;379 let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);380 if approved_list_exists381 {382 let list_itm = <ApprovedList<T>>::get(collection_id, item_id);383 approved = list_itm.contains(&recipient.clone());384 }385386 if !approved387 {388 Self::check_owner_or_admin_permissions(collection_id, sender)?;389 }390 391 let target_collection = <Collection<T>>::get(collection_id);392393 // TODO: implement other modes394 ensure!(target_collection.mode == CollectionMode::NFT, "Collection type not implemented");395396 if target_collection.mode == CollectionMode::NFT397 {398 Self::transfer_nft(collection_id, item_id, recipient)?;399 }400401 Ok(())402 }403404 #[weight = 0]405 pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {406407 // let no_perm_mes = "You do not have permissions to modify this collection";408 // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);409 // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));410 // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);411412 // // on_nft_received call413414 // Self::transfer(origin, collection_id, item_id, new_owner)?;415416 Ok(())417 }418 }419}420421impl<T: Trait> Module<T> {422423 fn collection_exists(collection_id: u64) -> DispatchResult{424 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");425 Ok(())426 }427428 fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {429430 Self::collection_exists(collection_id)?;431432 let target_collection = <Collection<T>>::get(collection_id);433 ensure!(subject == target_collection.owner, "You do not own this collection");434435 Ok(())436 }437438 fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {439440 Self::collection_exists(collection_id)?;441442 let target_collection = <Collection<T>>::get(collection_id);443 let is_owner = subject == target_collection.owner;444445 let no_perm_mes = "You do not have permissions to modify this collection";446 let exists = <AdminList<T>>::contains_key(collection_id);447448 if !is_owner449 {450 ensure!(exists, no_perm_mes);451 ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);452 }453 Ok(())454 }455456 fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{457458 let mut result = false;459 let target_collection = <Collection<T>>::get(collection_id);460461 if target_collection.mode == CollectionMode::NFT462 {463 let item = <NftItemList<T>>::get(collection_id, item_id);464 result = item.owner == subject;465 }466467 if target_collection.mode == CollectionMode::Fungible468 {469 let item = <FungibleItemList<T>>::get(collection_id, item_id);470 result = item.owner.contains(&subject);471 }472473 if target_collection.mode == CollectionMode::ReFungible474 {475 let item = <ReFungibleItemList<T>>::get(collection_id, item_id);476 result = item.owner.iter().any(|i| i.owner == subject);477 }478479 result480 }481482 fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {483484 let current_index = <ItemListIndex>::get(item.collection)485 .checked_add(1)486 .expect("Item list index id error");487488 Self::add_token_index(item.collection, current_index, item.owner.clone())?;489490 <ItemListIndex>::insert(item.collection, current_index);491 <NftItemList<T>>::insert(item.collection, current_index, item);492493 Ok(())494 }495496 fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {497 498 let item = <NftItemList<T>>::get(collection_id, item_id);499 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;500501 // update balance502 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();503 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);504 <NftItemList<T>>::remove(collection_id, item_id);505506 Ok(())507 }508509 fn transfer_nft(collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {510511 let mut item = <NftItemList<T>>::get(collection_id, item_id);512513 // update balance514 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();515 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);516517 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();518 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);519520 // change owner521 let old_owner = item.owner.clone();522 item.owner = new_owner.clone();523 <NftItemList<T>>::insert(collection_id, item_id, item);524525 // update index collection526 Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;527528 // reset approved list529 let itm: Vec<T::AccountId> = Vec::new();530 <ApprovedList<T>>::insert(collection_id, item_id, itm);531532 Ok(())533 }534535 fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {536 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());537 if list_exists {538 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());539 let item_contains = list.contains(&item_index.clone());540541 if !item_contains {542 list.push(item_index.clone());543 }544545 <AddressTokens<T>>::insert(collection_id, owner.clone(), list);546 } else {547 let mut itm = Vec::new();548 itm.push(item_index.clone());549 <AddressTokens<T>>::insert(collection_id, owner, itm);550 }551552 Ok(())553 }554555 fn remove_token_index(556 collection_id: u64,557 item_index: u64,558 owner: T::AccountId,559 ) -> DispatchResult {560 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());561 if list_exists {562 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());563 let item_contains = list.contains(&item_index.clone());564565 if item_contains {566 list.retain(|&item| item != item_index);567 <AddressTokens<T>>::insert(collection_id, owner, list);568 }569 }570571 Ok(())572 }573574 fn move_token_index(575 collection_id: u64,576 item_index: u64,577 old_owner: T::AccountId,578 new_owner: T::AccountId,579 ) -> DispatchResult {580 Self::remove_token_index(collection_id, item_index, old_owner)?;581 Self::add_token_index(collection_id, item_index, new_owner)?;582583 Ok(())584 }585}