difftreelog
Smart contract added
in: master
6 files changed
pallets/nft/src/lib.rsdiffbeforeafterboth1#![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 name: Vec<u16>, // 64 include null escape char28 pub description: Vec<u16>, // 256 include null escape char29 pub token_prefix: Vec<u8>, // 16 include null escape char30 pub custom_data_size: u32,31}3233#[derive(Encode, Decode, Default, Clone, PartialEq)]34#[cfg_attr(feature = "std", derive(Debug))]35pub struct CollectionAdminsType<AccountId> {36 pub admin: AccountId,37 pub collection_id: u64,38}3940#[derive(Encode, Decode, Default, Clone, PartialEq)]41#[cfg_attr(feature = "std", derive(Debug))]42pub struct NftItemType<AccountId> {43 pub collection: u64,44 pub owner: AccountId,45 pub data: Vec<u8>,46}4748/// The pallet's configuration trait.49pub trait Trait: system::Trait {50 // Add other types and constants required to configure this pallet.5152 /// The overarching event type.53 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;54}5556// This pallet's storage items.57decl_storage! {58 // It is important to update your storage name so that your pallet's59 // storage items are isolated from other pallets.60 trait Store for Module<T: Trait> as Nft {6162 /// Next available collection ID63 pub NextCollectionID get(fn next_collection_id): u64;64 pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;65 pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;6667 /// Balance owner per collection map68 pub Balance get(fn balance_count): map hasher(blake2_128_concat) (u64, T::AccountId) => u64;69 pub ApprovedList get(fn approved): map hasher(blake2_128_concat) (u64, u64) => Vec<T::AccountId>;7071 pub ItemList get(fn item_id): map hasher(blake2_128_concat) (u64, u64) => NftItemType<T::AccountId>;72 pub ItemListIndex get(fn item_index): map hasher(blake2_128_concat) u64 => u64;7374 pub AddressTokens get(fn address_tokens): map hasher(blake2_128_concat) (u64, T::AccountId) => Vec<u64>;7576 }77}7879// The pallet's events80decl_event!(81 pub enum Event<T>82 where83 AccountId = <T as system::Trait>::AccountId,84 {85 Created(u64, AccountId),86 ItemCreated(u64),87 ItemDestroyed(u64, u64),88 }89);9091// The pallet's dispatchable functions.92decl_module! {93 /// The module declaration.94 pub struct Module<T: Trait> for enum Call where origin: T::Origin {9596 // Initializing events97 // this is needed only if you are using events in your pallet98 fn deposit_event() = 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 = 0]110 pub fn create_collection( origin, 111 collection_name: Vec<u16>, 112 collection_description: Vec<u16>, 113 token_prefix: Vec<u8>, 114 custom_data_sz: u32) -> DispatchResult {115116 // Anyone can create a collection117 let who = ensure_signed(origin)?;118119 // check params 120 let mut name = collection_name.to_vec();121 name.push(0);122 ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");123124 let mut description = collection_description.to_vec();125 description.push(0);126 ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");127128 let mut prefix = token_prefix.to_vec();129 prefix.push(0);130 ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");131132 // Generate next collection ID133 let next_id = NextCollectionID::get();134135 NextCollectionID::put(next_id);136137 // Create new collection138 let new_collection = CollectionType {139 owner: who.clone(),140 name: name,141 description: description,142 token_prefix: prefix,143 next_item_id: next_id,144 custom_data_size: custom_data_sz,145 };146147 // Add new collection to map148 <Collection<T>>::insert(next_id, new_collection);149150 // call event151 Self::deposit_event(RawEvent::Created(next_id, who.clone()));152153 Ok(())154 }155156 #[weight = 0]157 pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {158159 let sender = ensure_signed(origin)?;160 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");161162 let owner = <Collection<T>>::get(collection_id).owner;163 ensure!(sender == owner, "You do not own this collection");164 <Collection<T>>::remove(collection_id);165166 Ok(())167 }168169 #[weight = 0]170 pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {171172 let sender = ensure_signed(origin)?;173 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");174175 let mut target_collection = <Collection<T>>::get(collection_id);176 ensure!(sender == target_collection.owner, "You do not own this collection");177178 target_collection.owner = new_owner;179 <Collection<T>>::insert(collection_id, target_collection);180181 Ok(())182 }183184 #[weight = 0]185 pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {186187 let sender = ensure_signed(origin)?;188 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");189190 let target_collection = <Collection<T>>::get(collection_id);191 let is_owner = sender == target_collection.owner;192193 let no_perm_mes = "You do not have permissions to modify this collection";194 let exists = <AdminList<T>>::contains_key(collection_id);195196 if !is_owner197 {198 ensure!(exists, no_perm_mes);199 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);200 }201202 let mut admin_arr: Vec<T::AccountId> = Vec::new();203 if exists204 {205 admin_arr = <AdminList<T>>::get(collection_id);206 ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");207 }208209 admin_arr.push(new_admin_id);210 <AdminList<T>>::insert(collection_id, admin_arr);211212 Ok(())213 }214215 #[weight = 0]216 pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {217218 let sender = ensure_signed(origin)?;219 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");220221 let target_collection = <Collection<T>>::get(collection_id);222 let is_owner = sender == target_collection.owner;223224 let no_perm_mes = "You do not have permissions to modify this collection";225 let exists = <AdminList<T>>::contains_key(collection_id);226227 if !is_owner228 {229 ensure!(exists, no_perm_mes);230 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);231 }232233 if exists234 {235 let mut admin_arr = <AdminList<T>>::get(collection_id);236 admin_arr.retain(|i| *i != account_id);237 <AdminList<T>>::insert(collection_id, admin_arr);238 }239240 Ok(())241 }242243 #[weight = 0]244 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>) -> DispatchResult {245246 let sender = ensure_signed(origin)?;247 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");248249 let target_collection = <Collection<T>>::get(collection_id);250 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");251 let is_owner = sender == target_collection.owner;252253 let no_perm_mes = "You do not have permissions to modify this collection";254 let exists = <AdminList<T>>::contains_key(collection_id);255256 if !is_owner257 {258 ensure!(exists, no_perm_mes);259 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);260 }261262 let new_balance = <Balance<T>>::get((collection_id, sender.clone())) + 1;263 <Balance<T>>::insert((collection_id, sender.clone()), new_balance);264265 // Create new item266 let new_item = NftItemType {267 collection: collection_id,268 owner: sender,269 data: properties,270 };271272273 let current_index = <ItemListIndex>::get(collection_id);274275 Self::add_token_index(collection_id, current_index, new_item.owner.clone())?;276277 <ItemListIndex>::insert(collection_id, current_index);278 <ItemList<T>>::insert((collection_id, current_index), new_item);279280 // call event281 Self::deposit_event(RawEvent::ItemCreated(collection_id));282283 Ok(())284 }285286 #[weight = 0]287 pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {288289 let sender = ensure_signed(origin)?;290 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");291292 let target_collection = <Collection<T>>::get(collection_id);293 let is_owner = sender == target_collection.owner;294295 ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");296 let item = <ItemList<T>>::get((collection_id, item_id));297298 if !is_owner299 {300 // check if item owner301 if item.owner != sender302 {303 let no_perm_mes = "You do not have permissions to modify this collection";304305 ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);306 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);307 }308 }309 <ItemList<T>>::remove((collection_id, item_id));310311 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;312313 // update balance314 let new_balance = <Balance<T>>::get((collection_id, item.owner.clone())) - 1;315 <Balance<T>>::insert((collection_id, item.owner.clone()), new_balance);316317 // call event318 Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));319320 Ok(())321 }322323 #[weight = 0]324 pub fn transfer(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {325326 let sender = ensure_signed(origin)?;327 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");328329 let target_collection = <Collection<T>>::get(collection_id);330 let is_owner = sender == target_collection.owner;331332 ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");333 let mut item = <ItemList<T>>::get((collection_id, item_id));334335 if !is_owner336 {337 // check if item owner338 if item.owner != sender339 {340 let no_perm_mes = "You do not have permissions to modify this collection";341342 ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);343 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);344 }345 }346 <ItemList<T>>::remove((collection_id, item_id));347348 // update balance349 let balance_old_owner = <Balance<T>>::get((collection_id, item.owner.clone())) - 1;350 <Balance<T>>::insert((collection_id, item.owner.clone()), balance_old_owner);351352 let balance_new_owner = <Balance<T>>::get((collection_id, new_owner.clone())) + 1;353 <Balance<T>>::insert((collection_id, new_owner.clone()), balance_new_owner);354355 // change owner356 let old_owner = item.owner.clone();357 item.owner = new_owner.clone();358 <ItemList<T>>::insert((collection_id, item_id), item);359360 // update index collection361 Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;362363 // reset approved list364 let itm: Vec<T::AccountId> = Vec::new();365 <ApprovedList<T>>::insert((collection_id, item_id), itm);366367 Ok(())368 }369370 #[weight = 0]371 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {372373 let sender = ensure_signed(origin)?;374 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");375376 let target_collection = <Collection<T>>::get(collection_id);377 let is_owner = sender == target_collection.owner;378379 ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");380 let item = <ItemList<T>>::get((collection_id, item_id));381382 if !is_owner383 {384 // check if item owner385 if item.owner != sender386 {387 let no_perm_mes = "You do not have permissions to modify this collection";388389 ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);390 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);391 }392 }393394 let list_exists = <ApprovedList<T>>::contains_key((collection_id, item_id));395 if list_exists {396397 let mut list = <ApprovedList<T>>::get((collection_id, item_id));398 let item_contains = list.contains(&approved.clone());399400 if !item_contains {401 list.push(approved.clone());402 }403 } else {404405 let mut itm = Vec::new();406 itm.push(approved.clone());407 <ApprovedList<T>>::insert((collection_id, item_id), itm);408 }409410 Ok(())411 }412413 #[weight = 0]414 pub fn transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {415416 let no_perm_mes = "You do not have permissions to modify this collection";417 ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);418 let list_itm = <ApprovedList<T>>::get((collection_id, item_id));419 ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);420421 Self::transfer(origin, collection_id, item_id, new_owner)?;422423 Ok(())424 }425426 #[weight = 0]427 pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {428429 let no_perm_mes = "You do not have permissions to modify this collection";430 ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);431 let list_itm = <ApprovedList<T>>::get((collection_id, item_id));432 ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);433434 // on_nft_received call435436 Self::transfer(origin, collection_id, item_id, new_owner)?;437438 Ok(())439 }440 }441}442443444impl<T: Trait> Module<T> {445 fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {446 447 let list_exists = <AddressTokens<T>>::contains_key((collection_id, owner.clone()));448 if list_exists {449450 let mut list = <AddressTokens<T>>::get((collection_id, owner.clone()));451 let item_contains = list.contains(&item_index.clone());452453 if !item_contains {454 list.push(item_index.clone());455 }456457 <AddressTokens<T>>::insert((collection_id, owner.clone()), list);458459 } else {460461 let mut itm = Vec::new();462 itm.push(item_index.clone());463 <AddressTokens<T>>::insert((collection_id, owner), itm);464 }465466 Ok(())467 }468469 fn remove_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {470 471 let list_exists = <AddressTokens<T>>::contains_key((collection_id, owner.clone()));472 if list_exists {473474 let mut list = <AddressTokens<T>>::get((collection_id, owner.clone()));475 let item_contains = list.contains(&item_index.clone());476477 if item_contains {478 list.retain(|&item| item != item_index);479 <AddressTokens<T>>::insert((collection_id, owner), list);480 }481 }482483 Ok(())484 }485486 fn move_token_index(collection_id: u64, item_index: u64, old_owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {487 488 Self::remove_token_index(collection_id, item_index, old_owner)?;489 Self::add_token_index(collection_id, item_index, new_owner)?;490 491 Ok(())492 }493}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 name: Vec<u16>, // 64 include null escape char28 pub description: Vec<u16>, // 256 include null escape char29 pub token_prefix: Vec<u8>, // 16 include null escape char30 pub custom_data_size: u32,31}3233#[derive(Encode, Decode, Default, Clone, PartialEq)]34#[cfg_attr(feature = "std", derive(Debug))]35pub struct CollectionAdminsType<AccountId> {36 pub admin: AccountId,37 pub collection_id: u64,38}3940#[derive(Encode, Decode, Default, Clone, PartialEq)]41#[cfg_attr(feature = "std", derive(Debug))]42pub struct NftItemType<AccountId> {43 pub collection: u64,44 pub owner: AccountId,45 pub data: Vec<u8>,46}4748/// The pallet's configuration trait.49pub trait Trait: system::Trait {50 // Add other types and constants required to configure this pallet.5152 /// The overarching event type.53 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;54}5556// This pallet's storage items.57decl_storage! {58 // It is important to update your storage name so that your pallet's59 // storage items are isolated from other pallets.60 trait Store for Module<T: Trait> as Nft {6162 /// Next available collection ID63 pub NextCollectionID get(fn next_collection_id): u64;64 pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;65 pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;6667 /// Balance owner per collection map68 pub Balance get(fn balance_count): map hasher(blake2_128_concat) (u64, T::AccountId) => u64;69 pub ApprovedList get(fn approved): map hasher(blake2_128_concat) (u64, u64) => Vec<T::AccountId>;7071 pub ItemList get(fn item_id): map hasher(blake2_128_concat) (u64, u64) => NftItemType<T::AccountId>;72 pub ItemListIndex get(fn item_index): map hasher(blake2_128_concat) u64 => u64;7374 pub AddressTokens get(fn address_tokens): map hasher(blake2_128_concat) (u64, T::AccountId) => Vec<u64>;7576 }77}7879// The pallet's events80decl_event!(81 pub enum Event<T>82 where83 AccountId = <T as system::Trait>::AccountId,84 {85 Created(u64, AccountId),86 ItemCreated(u64),87 ItemDestroyed(u64, u64),88 }89);9091// The pallet's dispatchable functions.92decl_module! {93 /// The module declaration.94 pub struct Module<T: Trait> for enum Call where origin: T::Origin {9596 // Initializing events97 // this is needed only if you are using events in your pallet98 fn deposit_event() = 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 = 0]110 pub fn create_collection( origin, 111 collection_name: Vec<u16>, 112 collection_description: Vec<u16>, 113 token_prefix: Vec<u8>, 114 custom_data_sz: u32) -> DispatchResult {115116 // Anyone can create a collection117 let who = ensure_signed(origin)?;118119 // check params 120 let mut name = collection_name.to_vec();121 name.push(0);122 ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");123124 let mut description = collection_description.to_vec();125 description.push(0);126 ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");127128 let mut prefix = token_prefix.to_vec();129 prefix.push(0);130 ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");131132 // Generate next collection ID133 let next_id = NextCollectionID::get()134 .checked_add(1)135 .expect("collection id error");136137 NextCollectionID::put(next_id);138139 // Create new collection140 let new_collection = CollectionType {141 owner: who.clone(),142 name: name,143 description: description,144 token_prefix: prefix,145 next_item_id: next_id,146 custom_data_size: custom_data_sz,147 };148149 // Add new collection to map150 <Collection<T>>::insert(next_id, new_collection);151152 // call event153 Self::deposit_event(RawEvent::Created(next_id, who.clone()));154155 Ok(())156 }157158 #[weight = 0]159 pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {160161 let sender = ensure_signed(origin)?;162 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");163164 let owner = <Collection<T>>::get(collection_id).owner;165 ensure!(sender == owner, "You do not own this collection");166 <Collection<T>>::remove(collection_id);167168 Ok(())169 }170171 #[weight = 0]172 pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {173174 let sender = ensure_signed(origin)?;175 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");176177 let mut target_collection = <Collection<T>>::get(collection_id);178 ensure!(sender == target_collection.owner, "You do not own this collection");179180 target_collection.owner = new_owner;181 <Collection<T>>::insert(collection_id, target_collection);182183 Ok(())184 }185186 #[weight = 0]187 pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {188189 let sender = ensure_signed(origin)?;190 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");191192 let target_collection = <Collection<T>>::get(collection_id);193 let is_owner = sender == target_collection.owner;194195 let no_perm_mes = "You do not have permissions to modify this collection";196 let exists = <AdminList<T>>::contains_key(collection_id);197198 if !is_owner199 {200 ensure!(exists, no_perm_mes);201 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);202 }203204 let mut admin_arr: Vec<T::AccountId> = Vec::new();205 if exists206 {207 admin_arr = <AdminList<T>>::get(collection_id);208 ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");209 }210211 admin_arr.push(new_admin_id);212 <AdminList<T>>::insert(collection_id, admin_arr);213214 Ok(())215 }216217 #[weight = 0]218 pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {219220 let sender = ensure_signed(origin)?;221 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");222223 let target_collection = <Collection<T>>::get(collection_id);224 let is_owner = sender == target_collection.owner;225226 let no_perm_mes = "You do not have permissions to modify this collection";227 let exists = <AdminList<T>>::contains_key(collection_id);228229 if !is_owner230 {231 ensure!(exists, no_perm_mes);232 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);233 }234235 if exists236 {237 let mut admin_arr = <AdminList<T>>::get(collection_id);238 admin_arr.retain(|i| *i != account_id);239 <AdminList<T>>::insert(collection_id, admin_arr);240 }241242 Ok(())243 }244245 #[weight = 0]246 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>) -> DispatchResult {247248 let sender = ensure_signed(origin)?;249 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");250251 let target_collection = <Collection<T>>::get(collection_id);252 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");253 let is_owner = sender == target_collection.owner;254255 let no_perm_mes = "You do not have permissions to modify this collection";256 let exists = <AdminList<T>>::contains_key(collection_id);257258 if !is_owner259 {260 ensure!(exists, no_perm_mes);261 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);262 }263264 let new_balance = <Balance<T>>::get((collection_id, sender.clone())) + 1;265 <Balance<T>>::insert((collection_id, sender.clone()), new_balance);266267 // Create new item268 let new_item = NftItemType {269 collection: collection_id,270 owner: sender,271 data: properties,272 };273274275 let current_index = <ItemListIndex>::get(collection_id)276 .checked_add(1)277 .expect("Item list index id error");278279 Self::add_token_index(collection_id, current_index, new_item.owner.clone())?;280281 <ItemListIndex>::insert(collection_id, current_index);282 <ItemList<T>>::insert((collection_id, current_index), new_item);283284 // call event285 Self::deposit_event(RawEvent::ItemCreated(collection_id));286287 Ok(())288 }289290 #[weight = 0]291 pub fn burn_item(origin, collection_id: u64, item_id: u64) -> 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 item = <ItemList<T>>::get((collection_id, item_id));301302 if !is_owner303 {304 // check if item owner305 if item.owner != sender306 {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 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;316317 // update balance318 let new_balance = <Balance<T>>::get((collection_id, item.owner.clone())) - 1;319 <Balance<T>>::insert((collection_id, item.owner.clone()), new_balance);320321 // call event322 Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));323324 Ok(())325 }326327 #[weight = 0]328 pub fn transfer(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {329330 let sender = ensure_signed(origin)?;331 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");332333 let target_collection = <Collection<T>>::get(collection_id);334 let is_owner = sender == target_collection.owner;335336 ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");337 let mut item = <ItemList<T>>::get((collection_id, item_id));338339 if !is_owner340 {341 // check if item owner342 if item.owner != sender343 {344 let no_perm_mes = "You do not have permissions to modify this collection";345346 ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);347 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);348 }349 }350 <ItemList<T>>::remove((collection_id, item_id));351352 // update balance353 let balance_old_owner = <Balance<T>>::get((collection_id, item.owner.clone())) - 1;354 <Balance<T>>::insert((collection_id, item.owner.clone()), balance_old_owner);355356 let balance_new_owner = <Balance<T>>::get((collection_id, new_owner.clone())) + 1;357 <Balance<T>>::insert((collection_id, new_owner.clone()), balance_new_owner);358359 // change owner360 let old_owner = item.owner.clone();361 item.owner = new_owner.clone();362 <ItemList<T>>::insert((collection_id, item_id), item);363364 // update index collection365 Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;366367 // reset approved list368 let itm: Vec<T::AccountId> = Vec::new();369 <ApprovedList<T>>::insert((collection_id, item_id), itm);370371 Ok(())372 }373374 #[weight = 0]375 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {376377 let sender = ensure_signed(origin)?;378 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");379380 let target_collection = <Collection<T>>::get(collection_id);381 let is_owner = sender == target_collection.owner;382383 ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");384 let item = <ItemList<T>>::get((collection_id, item_id));385386 if !is_owner387 {388 // check if item owner389 if item.owner != sender390 {391 let no_perm_mes = "You do not have permissions to modify this collection";392393 ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);394 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);395 }396 }397398 let list_exists = <ApprovedList<T>>::contains_key((collection_id, item_id));399 if list_exists {400401 let mut list = <ApprovedList<T>>::get((collection_id, item_id));402 let item_contains = list.contains(&approved.clone());403404 if !item_contains {405 list.push(approved.clone());406 }407 } else {408409 let mut itm = Vec::new();410 itm.push(approved.clone());411 <ApprovedList<T>>::insert((collection_id, item_id), itm);412 }413414 Ok(())415 }416417 #[weight = 0]418 pub fn transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {419420 let no_perm_mes = "You do not have permissions to modify this collection";421 ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);422 let list_itm = <ApprovedList<T>>::get((collection_id, item_id));423 ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);424425 Self::transfer(origin, collection_id, item_id, new_owner)?;426427 Ok(())428 }429430 #[weight = 0]431 pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {432433 let no_perm_mes = "You do not have permissions to modify this collection";434 ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);435 let list_itm = <ApprovedList<T>>::get((collection_id, item_id));436 ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);437438 // on_nft_received call439440 Self::transfer(origin, collection_id, item_id, new_owner)?;441442 Ok(())443 }444 }445}446447448impl<T: Trait> Module<T> {449 fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {450 451 let list_exists = <AddressTokens<T>>::contains_key((collection_id, owner.clone()));452 if list_exists {453454 let mut list = <AddressTokens<T>>::get((collection_id, owner.clone()));455 let item_contains = list.contains(&item_index.clone());456457 if !item_contains {458 list.push(item_index.clone());459 }460461 <AddressTokens<T>>::insert((collection_id, owner.clone()), list);462463 } else {464465 let mut itm = Vec::new();466 itm.push(item_index.clone());467 <AddressTokens<T>>::insert((collection_id, owner), itm);468 }469470 Ok(())471 }472473 fn remove_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {474 475 let list_exists = <AddressTokens<T>>::contains_key((collection_id, owner.clone()));476 if list_exists {477478 let mut list = <AddressTokens<T>>::get((collection_id, owner.clone()));479 let item_contains = list.contains(&item_index.clone());480481 if item_contains {482 list.retain(|&item| item != item_index);483 <AddressTokens<T>>::insert((collection_id, owner), list);484 }485 }486487 Ok(())488 }489490 fn move_token_index(collection_id: u64, item_index: u64, old_owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {491 492 Self::remove_token_index(collection_id, item_index, old_owner)?;493 Self::add_token_index(collection_id, item_index, new_owner)?;494 495 Ok(())496 }497}smart_contract/nft/.gitignorediffbeforeafterboth--- /dev/null
+++ b/smart_contract/nft/.gitignore
@@ -0,0 +1,9 @@
+# Ignore build artifacts from the local tests sub-crate.
+/target/
+
+# Ignore backup files creates by cargo fmt.
+**/*.rs.bk
+
+# Remove Cargo.lock when creating an executable, leave it for libraries
+# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock
+Cargo.lock
smart_contract/nft/.ink/abi_gen/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/smart_contract/nft/.ink/abi_gen/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "abi-gen"
+version = "0.1.0"
+authors = ["Parity Technologies <admin@parity.io>"]
+edition = "2018"
+publish = false
+
+[[bin]]
+name = "abi-gen"
+path = "main.rs"
+
+[dependencies]
+contract = { path = "../..", package = "nft", default-features = false, features = ["ink-generate-abi"] }
+ink_lang = { version = "2", git = "https://github.com/paritytech/ink", tag = "latest-v2", package = "ink_lang", default-features = false, features = ["ink-generate-abi"] }
+serde = "1.0"
+serde_json = "1.0"
smart_contract/nft/.ink/abi_gen/main.rsdiffbeforeafterboth--- /dev/null
+++ b/smart_contract/nft/.ink/abi_gen/main.rs
@@ -0,0 +1,7 @@
+fn main() -> Result<(), std::io::Error> {
+ let abi = <contract::Nft as ink_lang::GenerateAbi>::generate_abi();
+ let contents = serde_json::to_string_pretty(&abi)?;
+ std::fs::create_dir("target").ok();
+ std::fs::write("target/metadata.json", contents)?;
+ Ok(())
+}
smart_contract/nft/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/smart_contract/nft/Cargo.toml
@@ -0,0 +1,73 @@
+[package]
+name = "nft"
+version = "0.1.0"
+authors = ["[your_name] <[your_email]>"]
+edition = "2018"
+
+[dependencies]
+
+ink_abi = { version = "2", git = "https://github.com/paritytech/ink", tag = "latest-v2", package = "ink_abi", default-features = false, features = ["derive"], optional = true }
+ink_primitives = { version = "2", git = "https://github.com/paritytech/ink", tag = "latest-v2", package = "ink_primitives", default-features = false }
+ink_core = { version = "2", git = "https://github.com/paritytech/ink", tag = "latest-v2", package = "ink_core", default-features = false }
+ink_lang = { version = "2", git = "https://github.com/paritytech/ink", tag = "latest-v2", package = "ink_lang", default-features = false }
+scale = { package = "parity-scale-codec", version = "1.2", default-features = false, features = ["derive"] }
+
+sp-core = { git = "https://github.com/paritytech/substrate/", package = "sp-core", default-features = false }
+sp-runtime = { git = "https://github.com/paritytech/substrate/", package = "sp-runtime", default-features = false }
+sp-io = { git = "https://github.com/paritytech/substrate/", package = "sp-io", default-features = false, features = ["disable_panic_handler", "disable_oom", "disable_allocator"] }
+pallet-indices = { git = "https://github.com/paritytech/substrate/", package = "pallet-indices", default-features = false }
+
+
+[dependencies.type-metadata]
+git = "https://github.com/type-metadata/type-metadata.git"
+rev = "02eae9f35c40c943b56af5b60616219f2b72b47d"
+default-features = false
+features = ["derive"]
+optional = true
+
+[lib]
+name = "nft"
+path = "lib.rs"
+crate-type = [
+ # Used for normal contract Wasm blobs.
+ "cdylib",
+ # Required for ABI generation, and using this contract as a dependency.
+ # If using `cargo contract build`, it will be automatically disabled to produce a smaller Wasm binary
+ "rlib",
+]
+
+[features]
+default = ["test-env"]
+std = [
+ "ink_abi/std",
+ "ink_core/std",
+ "ink_primitives/std",
+ "scale/std",
+ "type-metadata/std",
+]
+test-env = [
+ "std",
+ "ink_lang/test-env",
+]
+ink-generate-abi = [
+ "std",
+ "ink_abi",
+ "type-metadata",
+ "ink_core/ink-generate-abi",
+ "ink_lang/ink-generate-abi",
+]
+ink-as-dependency = []
+
+[profile.release]
+panic = "abort"
+lto = true
+opt-level = "z"
+overflow-checks = true
+
+[workspace]
+members = [
+ ".ink/abi_gen"
+]
+exclude = [
+ ".ink"
+]
smart_contract/nft/lib.rsdiffbeforeafterboth--- /dev/null
+++ b/smart_contract/nft/lib.rs
@@ -0,0 +1,215 @@
+#![cfg_attr(not(feature = "std"), no_std)]
+
+use ink_core::env::EnvTypes;
+use scale::{Codec, Decode, Encode};
+use sp_core::crypto::AccountId32;
+use sp_runtime::traits::Member;
+use pallet_indices::address::Address;
+use core::{array::TryFromSliceError, convert::TryFrom};
+use ink_core::env::Clear;
+
+use ink_lang as ink;
+
+/// The default SRML hash type.
+#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode)]
+pub struct Hash([u8; 32]);
+
+impl From<[u8; 32]> for Hash {
+ fn from(hash: [u8; 32]) -> Hash {
+ Hash(hash)
+ }
+}
+
+impl<'a> TryFrom<&'a [u8]> for Hash {
+ type Error = TryFromSliceError;
+
+ fn try_from(bytes: &'a [u8]) -> Result<Hash, TryFromSliceError> {
+ let hash = <[u8; 32]>::try_from(bytes)?;
+ Ok(Hash(hash))
+ }
+}
+
+impl AsRef<[u8]> for Hash {
+ fn as_ref(&self) -> &[u8] {
+ &self.0[..]
+ }
+}
+
+impl AsMut<[u8]> for Hash {
+ fn as_mut(&mut self) -> &mut [u8] {
+ &mut self.0[..]
+ }
+}
+
+impl Clear for Hash {
+ fn is_clear(&self) -> bool {
+ self.as_ref().iter().all(|&byte| byte == 0x00)
+ }
+
+ fn clear() -> Self {
+ Self([0x00; 32])
+ }
+}
+
+/// The default SRML moment type.
+pub type Moment = u64;
+
+/// The default SRML blocknumber type.
+pub type BlockNumber = u64;
+
+/// The default SRML AccountIndex type.
+pub type AccountIndex = u32;
+
+/// The default timestamp type.
+pub type Timestamp = u64;
+
+/// The default SRML balance type.
+pub type Balance = u128;
+
+#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Encode, Decode)]
+pub struct AccountId (AccountId32);
+
+impl From<AccountId32> for AccountId {
+ fn from(account: AccountId32) -> Self {
+ AccountId(account)
+ }
+}
+
+// #[cfg(feature = "ink-generate-abi")]
+// impl HasTypeId for AccountId {
+// fn type_id() -> TypeId {
+// TypeIdArray::new(32, MetaType::new::<u8>()).into()
+// }
+// }
+
+// #[cfg(feature = "ink-generate-abi")]
+// impl HasTypeDef for AccountId {
+// fn type_def() -> TypeDef {
+// TypeDef::builtin()
+// }
+// }
+
+/// Contract environment types defined in substrate node-runtime
+#[cfg_attr(feature = "ink-generate-abi", derive(Metadata))]
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum NodeRuntimeTypes {}
+
+impl ink_core::env::EnvTypes for NodeRuntimeTypes {
+ type AccountId = AccountId;
+ type Balance = Balance;
+ type Hash = Hash;
+ type Timestamp = Timestamp;
+ type BlockNumber = BlockNumber;
+ type Call = Call;
+}
+
+/// Default runtime Call type, a subset of the runtime Call module variants
+///
+/// The codec indices of the modules *MUST* match those in the concrete runtime.
+#[derive(Encode, Decode)]
+#[cfg_attr(feature = "std", derive(Clone, PartialEq, Eq))]
+pub enum Call {
+ #[codec(index = "6")]
+ Balances(Balances<NodeRuntimeTypes, AccountIndex>),
+}
+
+/// Generic Balance Call, could be used with other runtimes
+#[derive(Encode, Decode, Clone, PartialEq, Eq)]
+pub enum Balances<T, AccountIndex>
+where
+ T: EnvTypes,
+ T::AccountId: Member + Codec,
+ AccountIndex: Member + Codec,
+{
+ #[allow(non_camel_case_types)]
+ transfer(Address<T::AccountId, AccountIndex>, #[codec(compact)] T::Balance),
+ #[allow(non_camel_case_types)]
+ set_balance(
+ Address<T::AccountId, AccountIndex>,
+ #[codec(compact)] T::Balance,
+ #[codec(compact)] T::Balance,
+ ),
+}
+
+#[ink::contract(version = "0.1.0")]
+mod nft {
+ use ink_core::storage;
+
+ /// Defines the storage of your contract.
+ /// Add new fields to the below struct in order
+ /// to add new static storage fields to your contract.
+ #[ink(storage)]
+ struct Nft {
+ /// Stores a single `bool` value on the storage.
+ value: storage::Value<bool>,
+ }
+
+ impl Nft {
+ /// Constructor that initializes the `bool` value to the given `init_value`.
+ #[ink(constructor)]
+ fn new(&mut self, init_value: bool) {
+ self.value.set(init_value);
+ }
+
+ /// Constructor that initializes the `bool` value to `false`.
+ ///
+ /// Constructors can delegate to other constructors.
+ #[ink(constructor)]
+ fn default(&mut self) {
+ self.new(false)
+ }
+
+ /// A message that can be called on instantiated contracts.
+ /// This one flips the value of the stored `bool` from `true`
+ /// to `false` and vice versa.
+ #[ink(message)]
+ fn flip(&mut self) {
+ *self.value = !self.get();
+ }
+
+ /// Simply returns the current value of our `bool`.
+ #[ink(message)]
+ fn get(&self) -> bool {
+ *self.value
+ }
+ }
+}
+
+
+#[cfg(test)]
+mod tests {
+ use crate::{calls, AccountIndex, NodeRuntimeTypes};
+ use super::Call;
+
+ use node_runtime::{self, Runtime};
+ use pallet_indices::address;
+ use scale::{Decode, Encode};
+
+ #[test]
+ fn call_balance_transfer() {
+ let balance = 10_000;
+ let account_index = 0;
+
+ let contract_address = calls::Address::Index(account_index);
+ let contract_transfer =
+ calls::Balances::<NodeRuntimeTypes, AccountIndex>::transfer(contract_address, balance);
+ let contract_call = Call::Balances(contract_transfer);
+
+ let srml_address = address::Address::Index(account_index);
+ let srml_transfer = node_runtime::BalancesCall::<Runtime>::transfer(srml_address, balance);
+ let srml_call = node_runtime::Call::Balances(srml_transfer);
+
+ let contract_call_encoded = contract_call.encode();
+ let srml_call_encoded = srml_call.encode();
+
+ assert_eq!(srml_call_encoded, contract_call_encoded);
+
+ let srml_call_decoded: node_runtime::Call =
+ Decode::decode(&mut contract_call_encoded.as_slice())
+ .expect("Balances transfer call decodes to srml type");
+ let srml_call_encoded = srml_call_decoded.encode();
+ let contract_call_decoded: Call = Decode::decode(&mut srml_call_encoded.as_slice())
+ .expect("Balances transfer call decodes back to contract type");
+ assert!(contract_call == contract_call_decoded);
+ }
+}
\ No newline at end of file