difftreelog
warning removed
in: master
3 files changed
pallets/nft/src/lib.rsdiffbeforeafterboth1#![cfg_attr(not(feature = "std"), no_std)]23/// A FRAME pallet template with necessary imports45/// Feel free to remove or edit this file as needed.6/// If you change the name of this file, make sure to update its references in runtime/src/lib.rs7/// If you remove this file, you can remove those references89/// For more guidance on Substrate FRAME, see the example pallet10/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs1112use frame_support::{13 dispatch::DispatchResult, decl_module, decl_storage, decl_event,14 ensure,15};16use frame_system::{self as system, ensure_signed };17use codec::{Encode, Decode};18use sp_runtime::sp_std::prelude::Vec;1920#[cfg(test)]21mod mock;2223#[cfg(test)]24mod tests;2526#[derive(Encode, Decode, Default, Clone, PartialEq)]27#[cfg_attr(feature = "std", derive(Debug))]28pub struct CollectionType<AccountId> {29 pub owner: AccountId,30 pub next_item_id: u64,31 pub custom_data_size: u32,32}3334#[derive(Encode, Decode, Default, Clone, PartialEq)]35#[cfg_attr(feature = "std", derive(Debug))]36pub struct CollectionAdminsType<AccountId> {37 pub admin: AccountId,38 pub collection_id: u64,39}4041#[derive(Encode, Decode, Default, Clone, PartialEq)]42#[cfg_attr(feature = "std", derive(Debug))]43pub struct NftItemType<AccountId> {44 pub collection: u64,45 pub owner: AccountId,46 pub data: Vec<u8>,47}4849/// The pallet's configuration trait.50pub trait Trait: system::Trait {51 // Add other types and constants required to configure this pallet.5253 /// The overarching event type.54 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;55}5657// This pallet's storage items.58decl_storage! {59 // It is important to update your storage name so that your pallet's60 // storage items are isolated from other pallets.61 trait Store for Module<T: Trait> as Nft {6263 /// Next available collection ID64 pub NextCollectionID get(fn next_collection_id): u64;6566 /// Collection map67 pub Collection get(collection): map hasher(identity) u64 => CollectionType<T::AccountId>;6869 /// Admins map (collection)70 pub AdminList get(admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;7172 /// Balance owner per collection map73 pub Balance get(balance_count): map hasher(blake2_128_concat) (u64, T::AccountId) => u64;7475 pub ApprovedList get(approved): map hasher(blake2_128_concat) (u64, u64) => Vec<T::AccountId>;76 pub ItemList get(item_id): map hasher(blake2_128_concat) (u64, u64) => NftItemType<T::AccountId>;77 pub ItemListIndex get(item_index): map hasher(blake2_128_concat) u64 => u64;78 }79}8081// The pallet's events82decl_event!(83 pub enum Event<T> where AccountId = <T as system::Trait>::AccountId {84 Created(u32, AccountId),85 }86);8788// The pallet's dispatchable functions.89decl_module! {90 /// The module declaration.91 pub struct Module<T: Trait> for enum Call where origin: T::Origin {9293 // Initializing events94 // this is needed only if you are using events in your pallet95 fn deposit_event() = default;9697 // Initializing events98 // this is needed only if you are using events in your module99 // fn deposit_event<T>() = default;100101 // Create collection of NFT with given parameters102 //103 // @param customDataSz size of custom data in each collection item104 // returns collection ID105106 // Create collection of NFT with given parameters107 //108 // @param customDataSz size of custom data in each collection item109 // returns collection ID110 #[weight = frame_support::weights::SimpleDispatchInfo::default()]111 pub fn create_collection(origin, custom_data_sz: u32) -> DispatchResult {112 // Anyone can create a collection113 let who = ensure_signed(origin)?;114115 // Generate next collection ID116 let next_id = NextCollectionID::get()117 .checked_add(1)118 .expect("collection id error");119120 NextCollectionID::put(next_id);121122 // Create new collection123 let new_collection = CollectionType {124 owner: who,125 next_item_id: next_id,126 custom_data_size: custom_data_sz,127 };128 129 // Add new collection to map130 <Collection<T>>::insert(next_id, new_collection);131132 Ok(())133 }134135 #[weight = frame_support::weights::SimpleDispatchInfo::default()]136 pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {137138 let sender = ensure_signed(origin)?;139 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");140141 let owner = <Collection<T>>::get(collection_id).owner;142 ensure!(sender == owner, "You do not own this collection");143 <Collection<T>>::remove(collection_id);144145 Ok(())146 }147148 #[weight = frame_support::weights::SimpleDispatchInfo::default()]149 pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {150151 let sender = ensure_signed(origin)?;152 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");153154 let mut target_collection = <Collection<T>>::get(collection_id);155 ensure!(sender == target_collection.owner, "You do not own this collection");156157 target_collection.owner = new_owner;158 <Collection<T>>::insert(collection_id, target_collection);159160 Ok(())161 }162163 #[weight = frame_support::weights::SimpleDispatchInfo::default()]164 pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {165166 let sender = ensure_signed(origin)?;167 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");168169 let target_collection = <Collection<T>>::get(collection_id);170 let is_owner = sender == target_collection.owner;171172 let no_perm_mes = "You do not have permissions to modify this collection";173 let exists = <AdminList<T>>::contains_key(collection_id);174175 if !is_owner 176 {177 ensure!(exists, no_perm_mes);178 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);179 }180 181 let mut admin_arr: Vec<T::AccountId> = Vec::new();182 if exists183 {184 admin_arr = <AdminList<T>>::get(collection_id);185 ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");186 }187188 admin_arr.push(new_admin_id);189 <AdminList<T>>::insert(collection_id, admin_arr);190191 Ok(())192 }193194 #[weight = frame_support::weights::SimpleDispatchInfo::default()]195 pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {196197 let sender = ensure_signed(origin)?;198 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");199200 let target_collection = <Collection<T>>::get(collection_id);201 let is_owner = sender == target_collection.owner;202203 let no_perm_mes = "You do not have permissions to modify this collection";204 let exists = <AdminList<T>>::contains_key(collection_id);205206 if !is_owner 207 {208 ensure!(exists, no_perm_mes);209 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);210 }211212 if exists213 {214 let mut admin_arr = <AdminList<T>>::get(collection_id);215 admin_arr.retain(|i| *i != account_id);216 <AdminList<T>>::insert(collection_id, admin_arr);217 }218219 Ok(())220 }221222 #[weight = frame_support::weights::SimpleDispatchInfo::default()]223 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>) -> DispatchResult {224225 let sender = ensure_signed(origin)?;226 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");227228 let target_collection = <Collection<T>>::get(collection_id);229 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");230 let is_owner = sender == target_collection.owner;231232 let no_perm_mes = "You do not have permissions to modify this collection";233 let exists = <AdminList<T>>::contains_key(collection_id);234235 if !is_owner 236 {237 ensure!(exists, no_perm_mes);238 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);239 }240241 let new_balance = <Balance<T>>::get((collection_id, sender.clone())) + 1;242 <Balance<T>>::insert((collection_id, sender.clone()), new_balance);243244 // Create new item245 let new_item = NftItemType {246 collection: collection_id,247 owner: sender,248 data: properties,249 };250251 let current_index = <ItemListIndex>::get(collection_id) + 1;252 <ItemListIndex>::insert(collection_id, current_index);253 <ItemList<T>>::insert((collection_id, current_index), new_item);254255 Ok(())256 }257258 #[weight = frame_support::weights::SimpleDispatchInfo::default()]259 pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {260261 let sender = ensure_signed(origin)?;262 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");263264 let target_collection = <Collection<T>>::get(collection_id);265 let is_owner = sender == target_collection.owner;266267 ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");268 let item = <ItemList<T>>::get((collection_id, item_id));269270 if !is_owner 271 {272 // check if item owner273 if item.owner != sender 274 {275 let no_perm_mes = "You do not have permissions to modify this collection";276277 ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);278 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);279 }280 }281 <ItemList<T>>::remove((collection_id, item_id));282283 // update balance284 let new_balance = <Balance<T>>::get((collection_id, item.owner.clone())) - 1;285 <Balance<T>>::insert((collection_id, item.owner.clone()), new_balance);286287 Ok(())288 }289290 #[weight = frame_support::weights::SimpleDispatchInfo::default()]291 pub fn transfer(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {292293 let sender = ensure_signed(origin)?;294 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");295296 let target_collection = <Collection<T>>::get(collection_id);297 let is_owner = sender == target_collection.owner;298299 ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");300 let mut item = <ItemList<T>>::get((collection_id, item_id));301302 if !is_owner 303 {304 // check if item owner305 if item.owner != sender 306 {307 let no_perm_mes = "You do not have permissions to modify this collection";308309 ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);310 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);311 }312 }313 <ItemList<T>>::remove((collection_id, item_id));314315 // update balance316 let balance_old_owner = <Balance<T>>::get((collection_id, item.owner.clone())) - 1;317 <Balance<T>>::insert((collection_id, item.owner.clone()), balance_old_owner);318319 let balance_new_owner = <Balance<T>>::get((collection_id, new_owner.clone())) + 1;320 <Balance<T>>::insert((collection_id, new_owner.clone()), balance_new_owner);321322 // change owner323 item.owner = new_owner;324 <ItemList<T>>::insert((collection_id, item_id), item);325326 // reset approved list327 let itm: Vec<T::AccountId> = Vec::new();328 <ApprovedList<T>>::insert((collection_id, item_id), itm);329330 Ok(())331 }332333 #[weight = frame_support::weights::SimpleDispatchInfo::default()]334 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {335336 let sender = ensure_signed(origin)?;337 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");338339 let target_collection = <Collection<T>>::get(collection_id);340 let is_owner = sender == target_collection.owner;341342 ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");343 let item = <ItemList<T>>::get((collection_id, item_id));344345 if !is_owner 346 {347 // check if item owner348 if item.owner != sender 349 {350 let no_perm_mes = "You do not have permissions to modify this collection";351352 ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);353 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);354 }355 }356357 let list_exists = <ApprovedList<T>>::contains_key((collection_id, item_id));358 if list_exists {359 360 let mut list = <ApprovedList<T>>::get((collection_id, item_id));361 let item_contains = list.contains(&approved.clone());362363 if !item_contains {364 list.push(approved.clone());365 } 366 } else {367 368 let mut itm = Vec::new();369 itm.push(approved.clone());370 <ApprovedList<T>>::insert((collection_id, item_id), itm);371 }372373 Ok(())374 }375376 #[weight = frame_support::weights::SimpleDispatchInfo::default()]377 pub fn transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {378379 // let sender = ensure_signed(origin)?;380 // ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");381382 // let target_collection = <Collection<T>>::get(collection_id);383 // let is_owner = sender == target_collection.owner;384385 // ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");386 // let mut item = <ItemList<T>>::get((collection_id, item_id));387388 // if !is_owner 389 // {390 // let no_perm_mes = "You do not have permissions to modify this collection";391392 // // check if item owner393 // if item.owner != sender 394 // {395 // ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);396 // ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);397 // }398399 // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);400 // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));401 // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);402403 // }404405406 let no_perm_mes = "You do not have permissions to modify this collection";407 ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);408 let list_itm = <ApprovedList<T>>::get((collection_id, item_id));409 ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);410411 Self::transfer(origin, collection_id, item_id, new_owner);412413 Ok(())414 }415 }416}1#![cfg_attr(not(feature = "std"), no_std)]23use codec::{Decode, Encode};4/// A FRAME pallet template with necessary imports56/// Feel free to remove or edit this file as needed.7/// If you change the name of this file, make sure to update its references in runtime/src/lib.rs8/// If you remove this file, you can remove those references910/// For more guidance on Substrate FRAME, see the example pallet11/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs12use frame_support::{decl_event, decl_module, decl_storage, dispatch::DispatchResult, ensure};13use frame_system::{self as system, ensure_signed};14use sp_runtime::sp_std::prelude::Vec;1516#[cfg(test)]17mod mock;1819#[cfg(test)]20mod tests;2122#[derive(Encode, Decode, Default, Clone, PartialEq)]23#[cfg_attr(feature = "std", derive(Debug))]24pub struct CollectionType<AccountId> {25 pub owner: AccountId,26 pub next_item_id: u64,27 pub custom_data_size: u32,28}2930#[derive(Encode, Decode, Default, Clone, PartialEq)]31#[cfg_attr(feature = "std", derive(Debug))]32pub struct CollectionAdminsType<AccountId> {33 pub admin: AccountId,34 pub collection_id: u64,35}3637#[derive(Encode, Decode, Default, Clone, PartialEq)]38#[cfg_attr(feature = "std", derive(Debug))]39pub struct NftItemType<AccountId> {40 pub collection: u64,41 pub owner: AccountId,42 pub data: Vec<u8>,43}4445/// The pallet's configuration trait.46pub trait Trait: system::Trait {47 // Add other types and constants required to configure this pallet.4849 /// The overarching event type.50 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;51}5253// This pallet's storage items.54decl_storage! {55 // It is important to update your storage name so that your pallet's56 // storage items are isolated from other pallets.57 trait Store for Module<T: Trait> as Nft {5859 /// Next available collection ID60 pub NextCollectionID get(fn next_collection_id): u64;6162 /// Collection map63 pub Collection get(collection): map hasher(identity) u64 => CollectionType<T::AccountId>;6465 /// Admins map (collection)66 pub AdminList get(admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;6768 /// Balance owner per collection map69 pub Balance get(balance_count): map hasher(blake2_128_concat) (u64, T::AccountId) => u64;7071 pub ApprovedList get(approved): map hasher(blake2_128_concat) (u64, u64) => Vec<T::AccountId>;72 pub ItemList get(item_id): map hasher(blake2_128_concat) (u64, u64) => NftItemType<T::AccountId>;73 pub ItemListIndex get(item_index): map hasher(blake2_128_concat) u64 => u64;74 }75}7677// The pallet's events78decl_event!(79 pub enum Event<T>80 where81 AccountId = <T as system::Trait>::AccountId,82 {83 Created(u32, AccountId),84 }85);8687// The pallet's dispatchable functions.88decl_module! {89 /// The module declaration.90 pub struct Module<T: Trait> for enum Call where origin: T::Origin {9192 // Initializing events93 // this is needed only if you are using events in your pallet94 fn deposit_event() = default;9596 // Initializing events97 // this is needed only if you are using events in your module98 // fn deposit_event<T>() = default;99100 // Create collection of NFT with given parameters101 //102 // @param customDataSz size of custom data in each collection item103 // returns collection ID104105 // Create collection of NFT with given parameters106 //107 // @param customDataSz size of custom data in each collection item108 // returns collection ID109 #[weight = frame_support::weights::SimpleDispatchInfo::default()]110 pub fn create_collection(origin, custom_data_sz: u32) -> DispatchResult {111 // Anyone can create a collection112 let who = ensure_signed(origin)?;113114 // Generate next collection ID115 let next_id = NextCollectionID::get()116 .checked_add(1)117 .expect("collection id error");118119 NextCollectionID::put(next_id);120121 // Create new collection122 let new_collection = CollectionType {123 owner: who,124 next_item_id: next_id,125 custom_data_size: custom_data_sz,126 };127128 // Add new collection to map129 <Collection<T>>::insert(next_id, new_collection);130131 Ok(())132 }133134 #[weight = frame_support::weights::SimpleDispatchInfo::default()]135 pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {136137 let sender = ensure_signed(origin)?;138 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");139140 let owner = <Collection<T>>::get(collection_id).owner;141 ensure!(sender == owner, "You do not own this collection");142 <Collection<T>>::remove(collection_id);143144 Ok(())145 }146147 #[weight = frame_support::weights::SimpleDispatchInfo::default()]148 pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {149150 let sender = ensure_signed(origin)?;151 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");152153 let mut target_collection = <Collection<T>>::get(collection_id);154 ensure!(sender == target_collection.owner, "You do not own this collection");155156 target_collection.owner = new_owner;157 <Collection<T>>::insert(collection_id, target_collection);158159 Ok(())160 }161162 #[weight = frame_support::weights::SimpleDispatchInfo::default()]163 pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {164165 let sender = ensure_signed(origin)?;166 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");167168 let target_collection = <Collection<T>>::get(collection_id);169 let is_owner = sender == target_collection.owner;170171 let no_perm_mes = "You do not have permissions to modify this collection";172 let exists = <AdminList<T>>::contains_key(collection_id);173174 if !is_owner175 {176 ensure!(exists, no_perm_mes);177 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);178 }179180 let mut admin_arr: Vec<T::AccountId> = Vec::new();181 if exists182 {183 admin_arr = <AdminList<T>>::get(collection_id);184 ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");185 }186187 admin_arr.push(new_admin_id);188 <AdminList<T>>::insert(collection_id, admin_arr);189190 Ok(())191 }192193 #[weight = frame_support::weights::SimpleDispatchInfo::default()]194 pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {195196 let sender = ensure_signed(origin)?;197 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");198199 let target_collection = <Collection<T>>::get(collection_id);200 let is_owner = sender == target_collection.owner;201202 let no_perm_mes = "You do not have permissions to modify this collection";203 let exists = <AdminList<T>>::contains_key(collection_id);204205 if !is_owner206 {207 ensure!(exists, no_perm_mes);208 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);209 }210211 if exists212 {213 let mut admin_arr = <AdminList<T>>::get(collection_id);214 admin_arr.retain(|i| *i != account_id);215 <AdminList<T>>::insert(collection_id, admin_arr);216 }217218 Ok(())219 }220221 #[weight = frame_support::weights::SimpleDispatchInfo::default()]222 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>) -> DispatchResult {223224 let sender = ensure_signed(origin)?;225 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");226227 let target_collection = <Collection<T>>::get(collection_id);228 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");229 let is_owner = sender == target_collection.owner;230231 let no_perm_mes = "You do not have permissions to modify this collection";232 let exists = <AdminList<T>>::contains_key(collection_id);233234 if !is_owner235 {236 ensure!(exists, no_perm_mes);237 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);238 }239240 let new_balance = <Balance<T>>::get((collection_id, sender.clone())) + 1;241 <Balance<T>>::insert((collection_id, sender.clone()), new_balance);242243 // Create new item244 let new_item = NftItemType {245 collection: collection_id,246 owner: sender,247 data: properties,248 };249250 let current_index = <ItemListIndex>::get(collection_id) + 1;251 <ItemListIndex>::insert(collection_id, current_index);252 <ItemList<T>>::insert((collection_id, current_index), new_item);253254 Ok(())255 }256257 #[weight = frame_support::weights::SimpleDispatchInfo::default()]258 pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {259260 let sender = ensure_signed(origin)?;261 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");262263 let target_collection = <Collection<T>>::get(collection_id);264 let is_owner = sender == target_collection.owner;265266 ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");267 let item = <ItemList<T>>::get((collection_id, item_id));268269 if !is_owner270 {271 // check if item owner272 if item.owner != sender273 {274 let no_perm_mes = "You do not have permissions to modify this collection";275276 ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);277 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);278 }279 }280 <ItemList<T>>::remove((collection_id, item_id));281282 // update balance283 let new_balance = <Balance<T>>::get((collection_id, item.owner.clone())) - 1;284 <Balance<T>>::insert((collection_id, item.owner.clone()), new_balance);285286 Ok(())287 }288289 #[weight = frame_support::weights::SimpleDispatchInfo::default()]290 pub fn transfer(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {291292 let sender = ensure_signed(origin)?;293 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");294295 let target_collection = <Collection<T>>::get(collection_id);296 let is_owner = sender == target_collection.owner;297298 ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");299 let mut item = <ItemList<T>>::get((collection_id, item_id));300301 if !is_owner302 {303 // check if item owner304 if item.owner != sender305 {306 let no_perm_mes = "You do not have permissions to modify this collection";307308 ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);309 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);310 }311 }312 <ItemList<T>>::remove((collection_id, item_id));313314 // update balance315 let balance_old_owner = <Balance<T>>::get((collection_id, item.owner.clone())) - 1;316 <Balance<T>>::insert((collection_id, item.owner.clone()), balance_old_owner);317318 let balance_new_owner = <Balance<T>>::get((collection_id, new_owner.clone())) + 1;319 <Balance<T>>::insert((collection_id, new_owner.clone()), balance_new_owner);320321 // change owner322 item.owner = new_owner;323 <ItemList<T>>::insert((collection_id, item_id), item);324325 // reset approved list326 let itm: Vec<T::AccountId> = Vec::new();327 <ApprovedList<T>>::insert((collection_id, item_id), itm);328329 Ok(())330 }331332 #[weight = frame_support::weights::SimpleDispatchInfo::default()]333 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {334335 let sender = ensure_signed(origin)?;336 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");337338 let target_collection = <Collection<T>>::get(collection_id);339 let is_owner = sender == target_collection.owner;340341 ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");342 let item = <ItemList<T>>::get((collection_id, item_id));343344 if !is_owner345 {346 // check if item owner347 if item.owner != sender348 {349 let no_perm_mes = "You do not have permissions to modify this collection";350351 ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);352 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);353 }354 }355356 let list_exists = <ApprovedList<T>>::contains_key((collection_id, item_id));357 if list_exists {358359 let mut list = <ApprovedList<T>>::get((collection_id, item_id));360 let item_contains = list.contains(&approved.clone());361362 if !item_contains {363 list.push(approved.clone());364 }365 } else {366367 let mut itm = Vec::new();368 itm.push(approved.clone());369 <ApprovedList<T>>::insert((collection_id, item_id), itm);370 }371372 Ok(())373 }374375 #[weight = frame_support::weights::SimpleDispatchInfo::default()]376 pub fn transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {377378 let no_perm_mes = "You do not have permissions to modify this collection";379 ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);380 let list_itm = <ApprovedList<T>>::get((collection_id, item_id));381 ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);382383 Self::transfer(origin, collection_id, item_id, new_owner)?;384385 Ok(())386 }387 }388}pallets/nft/src/mock.rsdiffbeforeafterboth--- a/pallets/nft/src/mock.rs
+++ b/pallets/nft/src/mock.rs
@@ -1,15 +1,17 @@
// Creating mock runtime here
use crate::{Module, Trait};
+use frame_support::{impl_outer_origin, parameter_types, weights::Weight};
+use frame_system as system;
use sp_core::H256;
-use frame_support::{impl_outer_origin, parameter_types, weights::Weight};
use sp_runtime::{
- traits::{BlakeTwo256, IdentityLookup}, testing::Header, Perbill,
+ testing::Header,
+ traits::{BlakeTwo256, IdentityLookup},
+ Perbill,
};
-use frame_system as system;
impl_outer_origin! {
- pub enum Origin for Test {}
+ pub enum Origin for Test {}
}
// For testing the pallet, we construct most of a mock runtime. This means
@@ -18,39 +20,42 @@
#[derive(Clone, Eq, PartialEq)]
pub struct Test;
parameter_types! {
- pub const BlockHashCount: u64 = 250;
- pub const MaximumBlockWeight: Weight = 1024;
- pub const MaximumBlockLength: u32 = 2 * 1024;
- pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);
+ pub const BlockHashCount: u64 = 250;
+ pub const MaximumBlockWeight: Weight = 1024;
+ pub const MaximumBlockLength: u32 = 2 * 1024;
+ pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);
}
impl system::Trait for Test {
- type Origin = Origin;
- type Call = ();
- type Index = u64;
- type BlockNumber = u64;
- type Hash = H256;
- type Hashing = BlakeTwo256;
- type AccountId = u64;
- type Lookup = IdentityLookup<Self::AccountId>;
- type Header = Header;
- type Event = ();
- type BlockHashCount = BlockHashCount;
- type MaximumBlockWeight = MaximumBlockWeight;
- type MaximumBlockLength = MaximumBlockLength;
- type AvailableBlockRatio = AvailableBlockRatio;
- type Version = ();
- type ModuleToIndex = ();
- type AccountData = ();
- type OnNewAccount = ();
- type OnKilledAccount = ();
+ type Origin = Origin;
+ type Call = ();
+ type Index = u64;
+ type BlockNumber = u64;
+ type Hash = H256;
+ type Hashing = BlakeTwo256;
+ type AccountId = u64;
+ type Lookup = IdentityLookup<Self::AccountId>;
+ type Header = Header;
+ type Event = ();
+ type BlockHashCount = BlockHashCount;
+ type MaximumBlockWeight = MaximumBlockWeight;
+ type MaximumBlockLength = MaximumBlockLength;
+ type AvailableBlockRatio = AvailableBlockRatio;
+ type Version = ();
+ type ModuleToIndex = ();
+ type AccountData = ();
+ type OnNewAccount = ();
+ type OnKilledAccount = ();
}
impl Trait for Test {
- type Event = ();
+ type Event = ();
}
pub type TemplateModule = Module<Test>;
// This function basically just builds a genesis storage key/value store according to
// our desired mockup.
pub fn new_test_ext() -> sp_io::TestExternalities {
- system::GenesisConfig::default().build_storage::<Test>().unwrap().into()
+ system::GenesisConfig::default()
+ .build_storage::<Test>()
+ .unwrap()
+ .into()
}
pallets/nft/src/tests.rsdiffbeforeafterboth--- a/pallets/nft/src/tests.rs
+++ b/pallets/nft/src/tests.rs
@@ -1,6 +1,6 @@
// Tests to be written here
-use crate::{ mock::*};
-use frame_support::{assert_ok, assert_noop};
+use crate::mock::*;
+use frame_support::{assert_noop, assert_ok};
#[test]
fn create_collection_test() {
@@ -14,69 +14,83 @@
#[test]
fn change_collection_owner() {
- new_test_ext().execute_with(|| {
+ new_test_ext().execute_with(|| {
let size = 1024;
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(origin1.clone(), size));
- assert_ok!(TemplateModule::change_collection_owner(origin1.clone(), 1, 2));
+ assert_ok!(TemplateModule::change_collection_owner(
+ origin1.clone(),
+ 1,
+ 2
+ ));
assert_eq!(TemplateModule::collection(1).owner, 2);
- });
+ });
}
#[test]
fn destroy_collection() {
- new_test_ext().execute_with(|| {
+ new_test_ext().execute_with(|| {
let size = 1024;
let origin1 = Origin::signed(1);
assert_ok!(TemplateModule::create_collection(origin1.clone(), size));
assert_ok!(TemplateModule::destroy_collection(origin1.clone(), 1));
- });
+ });
}
#[test]
fn create_item() {
- new_test_ext().execute_with(|| {
+ new_test_ext().execute_with(|| {
let size = 1024;
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
assert_ok!(TemplateModule::create_collection(origin1.clone(), size));
assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
- assert_ok!(TemplateModule::create_item(origin2.clone(), 1, [1,1,1].to_vec()));
+ assert_ok!(TemplateModule::create_item(
+ origin2.clone(),
+ 1,
+ [1, 1, 1].to_vec()
+ ));
// check balance (collection with id = 1, user id = 2)
assert_eq!(TemplateModule::balance_count((1, 2)), 1);
- });
+ });
}
#[test]
fn burn_item() {
- new_test_ext().execute_with(|| {
+ new_test_ext().execute_with(|| {
let size = 1024;
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
assert_ok!(TemplateModule::create_collection(origin1.clone(), size));
assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));
- assert_ok!(TemplateModule::create_item(origin2.clone(), 1, [1,1,1].to_vec()));
+ assert_ok!(TemplateModule::create_item(
+ origin2.clone(),
+ 1,
+ [1, 1, 1].to_vec()
+ ));
// check balance (collection with id = 1, user id = 2)
assert_eq!(TemplateModule::balance_count((1, 2)), 1);
// burn item
assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1));
- assert_noop!(TemplateModule::burn_item(origin1.clone(), 1, 1), "Item does not exists");
+ assert_noop!(
+ TemplateModule::burn_item(origin1.clone(), 1, 1),
+ "Item does not exists"
+ );
assert_eq!(TemplateModule::balance_count((1, 1)), 0);
- });
+ });
}
-
#[test]
fn add_collection_admin() {
- new_test_ext().execute_with(|| {
+ new_test_ext().execute_with(|| {
let size = 1024;
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -96,12 +110,12 @@
assert_eq!(TemplateModule::admin_list_collection(1).contains(&2), true);
assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), true);
- });
+ });
}
#[test]
fn remove_collection_admin() {
- new_test_ext().execute_with(|| {
+ new_test_ext().execute_with(|| {
let size = 1024;
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -123,14 +137,18 @@
assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), true);
// remove admin
- assert_ok!(TemplateModule::remove_collection_admin(origin2.clone(), 1, 3));
+ assert_ok!(TemplateModule::remove_collection_admin(
+ origin2.clone(),
+ 1,
+ 3
+ ));
assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), false);
- });
+ });
}
#[test]
fn balance_of() {
- new_test_ext().execute_with(|| {
+ new_test_ext().execute_with(|| {
let size = 1024;
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -148,17 +166,21 @@
assert_eq!(TemplateModule::balance_count((1, 1)), 0);
// create item
- assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,1,1].to_vec()));
-
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 1, 1].to_vec()
+ ));
+
// check balance (collection with id = 1, user id = 2)
assert_eq!(TemplateModule::balance_count((1, 1)), 1);
- assert_eq!(TemplateModule::item_id((1,1)).owner, 1);
- });
+ assert_eq!(TemplateModule::item_id((1, 1)).owner, 1);
+ });
}
#[test]
fn transfer() {
- new_test_ext().execute_with(|| {
+ new_test_ext().execute_with(|| {
let size = 1024;
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -173,21 +195,25 @@
assert_eq!(TemplateModule::collection(3).owner, 3);
// create item
- assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,1,1].to_vec()));
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 1, 1].to_vec()
+ ));
// transfer
assert_ok!(TemplateModule::transfer(origin1.clone(), 1, 1, 2));
- assert_eq!(TemplateModule::item_id((1,1)).owner, 2);
+ assert_eq!(TemplateModule::item_id((1, 1)).owner, 2);
// balance_of check
assert_eq!(TemplateModule::balance_count((1, 1)), 0);
assert_eq!(TemplateModule::balance_count((1, 2)), 1);
- });
+ });
}
#[test]
fn approve() {
- new_test_ext().execute_with(|| {
+ new_test_ext().execute_with(|| {
let size = 1024;
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -202,18 +228,21 @@
assert_eq!(TemplateModule::collection(3).owner, 3);
// create item
- assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,1,1].to_vec()));
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 1, 1].to_vec()
+ ));
// approve
assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
- assert_eq!(TemplateModule::approved((1,1)).contains(&2), true);
-
- });
+ assert_eq!(TemplateModule::approved((1, 1)).contains(&2), true);
+ });
}
#[test]
fn get_approved() {
- new_test_ext().execute_with(|| {
+ new_test_ext().execute_with(|| {
let size = 1024;
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -228,18 +257,21 @@
assert_eq!(TemplateModule::collection(3).owner, 3);
// create item
- assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,1,1].to_vec()));
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 1, 1].to_vec()
+ ));
// approve
assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
- assert_eq!(TemplateModule::approved((1,1)).contains(&2), true);
-
- });
+ assert_eq!(TemplateModule::approved((1, 1)).contains(&2), true);
+ });
}
#[test]
fn transfer_from() {
- new_test_ext().execute_with(|| {
+ new_test_ext().execute_with(|| {
let size = 1024;
let origin1 = Origin::signed(1);
let origin2 = Origin::signed(2);
@@ -254,11 +286,14 @@
assert_eq!(TemplateModule::collection(3).owner, 3);
// create item
- assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,1,1].to_vec()));
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 1, 1].to_vec()
+ ));
// approve
assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
assert_ok!(TemplateModule::transfer_from(origin1.clone(), 1, 1, 2));
-
- });
-}
\ No newline at end of file
+ });
+}