difftreelog
Offchain schema added
in: master
6 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3086,6 +3086,7 @@
"frame-support",
"frame-system",
"parity-scale-codec",
+ "serde",
"sp-core",
"sp-io",
"sp-runtime",
pallets/nft/Cargo.tomldiffbeforeafterboth--- a/pallets/nft/Cargo.toml
+++ b/pallets/nft/Cargo.toml
@@ -32,6 +32,10 @@
git = 'https://github.com/usetech-llc/substrate.git'
branch = 'rc4_ext_dispatch_reenabled'
version = '2.0.0-rc4'
+
+[dependencies]
+# third-party dependencies
+serde = { version = "1.0.102", features = ["derive"] }
[package]
authors = ['Substrate DevHub <https://github.com/substrate-developer-hub>']
@@ -49,6 +53,7 @@
default = ['std']
std = [
'codec/std',
+ "serde/std",
'frame-support/std',
'frame-system/std',
'sp-runtime/std',
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 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);313 if !item_owner314 {315 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;316 }317 318 Self::burn_nft_item(collection_id, item_id)?;319320 // call event321 Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));322323 Ok(())324 }325326 #[weight = 0]327 pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {328329 let sender = ensure_signed(origin)?;330 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);331 if !item_owner332 {333 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;334 }335336 let target_collection = <Collection<T>>::get(collection_id);337338 // TODO: implement other modes339 ensure!(target_collection.mode == CollectionMode::NFT, "Collection type not implemented");340341 if target_collection.mode == CollectionMode::NFT342 {343 Self::transfer_nft(collection_id, item_id, recipient)?;344 }345346 Ok(())347 }348349 #[weight = 0]350 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {351352 let sender = ensure_signed(origin)?;353354 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);355 if !item_owner356 {357 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;358 }359360 let list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);361 if list_exists {362363 let mut list = <ApprovedList<T>>::get(collection_id, item_id);364 let item_contains = list.contains(&approved.clone());365366 if !item_contains {367 list.push(approved.clone());368 }369 } else {370371 let mut itm = Vec::new();372 itm.push(approved.clone());373 <ApprovedList<T>>::insert(collection_id, item_id, itm);374 }375376 Ok(())377 }378379 #[weight = 0]380 pub fn transfer_from(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, ) -> DispatchResult {381382 let mut approved: bool = false; 383 let sender = ensure_signed(origin)?;384 let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);385 if approved_list_exists386 {387 let list_itm = <ApprovedList<T>>::get(collection_id, item_id);388 approved = list_itm.contains(&recipient.clone());389 }390391 if !approved392 {393 Self::check_owner_or_admin_permissions(collection_id, sender)?;394 }395 396 let target_collection = <Collection<T>>::get(collection_id);397398 // TODO: implement other modes399 ensure!(target_collection.mode == CollectionMode::NFT, "Collection type not implemented");400401 if target_collection.mode == CollectionMode::NFT402 {403 Self::transfer_nft(collection_id, item_id, recipient)?;404 }405406 Ok(())407 }408409 #[weight = 0]410 pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {411412 // let no_perm_mes = "You do not have permissions to modify this collection";413 // ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);414 // let list_itm = <ApprovedList<T>>::get((collection_id, item_id));415 // ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);416417 // // on_nft_received call418419 // Self::transfer(origin, collection_id, item_id, new_owner)?;420421 Ok(())422 }423 }424}425426impl<T: Trait> Module<T> {427428 fn collection_exists(collection_id: u64) -> DispatchResult{429 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");430 Ok(())431 }432433 fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {434435 Self::collection_exists(collection_id)?;436437 let target_collection = <Collection<T>>::get(collection_id);438 ensure!(subject == target_collection.owner, "You do not own this collection");439440 Ok(())441 }442443 fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {444445 Self::collection_exists(collection_id)?;446447 let target_collection = <Collection<T>>::get(collection_id);448 let is_owner = subject == target_collection.owner;449450 let no_perm_mes = "You do not have permissions to modify this collection";451 let exists = <AdminList<T>>::contains_key(collection_id);452453 if !is_owner454 {455 ensure!(exists, no_perm_mes);456 ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);457 }458 Ok(())459 }460461 fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{462463 let mut result = false;464 let target_collection = <Collection<T>>::get(collection_id);465466 if target_collection.mode == CollectionMode::NFT467 {468 let item = <NftItemList<T>>::get(collection_id, item_id);469 result = item.owner == subject;470 }471472 if target_collection.mode == CollectionMode::Fungible473 {474 let item = <FungibleItemList<T>>::get(collection_id, item_id);475 result = item.owner.contains(&subject);476 }477478 if target_collection.mode == CollectionMode::ReFungible479 {480 let item = <ReFungibleItemList<T>>::get(collection_id, item_id);481 result = item.owner.iter().any(|i| i.owner == subject);482 }483484 result485 }486487 fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {488489 let current_index = <ItemListIndex>::get(item.collection)490 .checked_add(1)491 .expect("Item list index id error");492493 Self::add_token_index(item.collection, current_index, item.owner.clone())?;494495 <ItemListIndex>::insert(item.collection, current_index);496 <NftItemList<T>>::insert(item.collection, current_index, item);497498 Ok(())499 }500501 fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {502 503 let item = <NftItemList<T>>::get(collection_id, item_id);504 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;505506 // update balance507 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();508 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);509 <NftItemList<T>>::remove(collection_id, item_id);510511 Ok(())512 }513514 fn transfer_nft(collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {515516 let mut item = <NftItemList<T>>::get(collection_id, item_id);517518 // update balance519 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();520 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);521522 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();523 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);524525 // change owner526 let old_owner = item.owner.clone();527 item.owner = new_owner.clone();528 <NftItemList<T>>::insert(collection_id, item_id, item);529530 // update index collection531 Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;532533 // reset approved list534 let itm: Vec<T::AccountId> = Vec::new();535 <ApprovedList<T>>::insert(collection_id, item_id, itm);536537 Ok(())538 }539540 fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {541 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());542 if list_exists {543 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());544 let item_contains = list.contains(&item_index.clone());545546 if !item_contains {547 list.push(item_index.clone());548 }549550 <AddressTokens<T>>::insert(collection_id, owner.clone(), list);551 } else {552 let mut itm = Vec::new();553 itm.push(item_index.clone());554 <AddressTokens<T>>::insert(collection_id, owner, itm);555 }556557 Ok(())558 }559560 fn remove_token_index(561 collection_id: u64,562 item_index: u64,563 owner: T::AccountId,564 ) -> DispatchResult {565 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());566 if list_exists {567 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());568 let item_contains = list.contains(&item_index.clone());569570 if item_contains {571 list.retain(|&item| item != item_index);572 <AddressTokens<T>>::insert(collection_id, owner, list);573 }574 }575576 Ok(())577 }578579 fn move_token_index(580 collection_id: u64,581 item_index: u64,582 old_owner: T::AccountId,583 new_owner: T::AccountId,584 ) -> DispatchResult {585 Self::remove_token_index(collection_id, item_index, old_owner)?;586 Self::add_token_index(collection_id, item_index, new_owner)?;587588 Ok(())589 }590}1#![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, Eq, Clone, PartialEq)]18pub enum CollectionMode {19 Invalid,20 // custom data size21 NFT(u32),22 // amount23 Fungible(u32),24 ReFungible,25}2627impl Into<u8> for CollectionMode {28 fn into(self) -> u8{29 match self {30 CollectionMode::Invalid => 0,31 CollectionMode::NFT(_) => 1,32 CollectionMode::Fungible(_) => 2,33 CollectionMode::ReFungible => 3,34 }35 }36}3738#[derive(Encode, Decode, Debug, Clone, PartialEq)]39pub enum AccessMode {40 Normal,41 WhiteList,42}43impl Default for AccessMode { fn default() -> Self { Self::Normal } }4445impl Default for CollectionMode { fn default() -> Self { Self::Invalid } }4647#[derive(Encode, Decode, Default, Clone, PartialEq)]48#[cfg_attr(feature = "std", derive(Debug))]49pub struct Ownership<AccountId> {50 pub owner: AccountId,51 pub fraction: u12852}5354#[derive(Encode, Decode, Default, Clone, PartialEq)]55#[cfg_attr(feature = "std", derive(Debug))]56pub struct CollectionType<AccountId> {57 pub owner: AccountId,58 pub mode: CollectionMode,59 pub access: AccessMode,60 pub next_item_id: u64,61 pub decimal_points: u32,62 pub name: Vec<u16>, // 64 include null escape char63 pub description: Vec<u16>, // 256 include null escape char64 pub token_prefix: Vec<u8>, // 16 include null escape char65 pub custom_data_size: u32,66 pub offchain_schema: Vec<u8>,67 pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender68 pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship69}7071#[derive(Encode, Decode, Default, Clone, PartialEq)]72#[cfg_attr(feature = "std", derive(Debug))]73pub struct CollectionAdminsType<AccountId> {74 pub admin: AccountId,75 pub collection_id: u64,76}7778#[derive(Encode, Decode, Default, Clone, PartialEq)]79#[cfg_attr(feature = "std", derive(Debug))]80pub struct NftItemType<AccountId> {81 pub collection: u64,82 pub owner: AccountId,83 pub data: Vec<u8>,84}8586#[derive(Encode, Decode, Default, Clone, PartialEq)]87#[cfg_attr(feature = "std", derive(Debug))]88pub struct FungibleItemType<AccountId> {89 pub collection: u64,90 pub owner: Vec<AccountId>,91 pub data: Vec<u64>,92}9394#[derive(Encode, Decode, Default, Clone, PartialEq)]95#[cfg_attr(feature = "std", derive(Debug))]96pub struct ReFungibleItemType<AccountId> {97 pub collection: u64,98 pub owner: Vec<Ownership<AccountId>>,99}100101pub trait Trait: system::Trait {102 type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;103}104105decl_storage! {106 trait Store for Module<T: Trait> as Nft {107108 // Private members109 NextCollectionID: u64;110 ItemListIndex: map hasher(blake2_128_concat) u64 => u64;111112 pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;113 pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;114115 // Balance owner per collection map116 pub Balance get(fn balance_count): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => u64;117 pub ApprovedList get(fn approved): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => Vec<T::AccountId>;118119 // Item collections120 pub NftItemList get(fn nft_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => NftItemType<T::AccountId>;121 pub FungibleItemList get(fn fungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => FungibleItemType<T::AccountId>;122 pub ReFungibleItemList get(fn refungible_item_id): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) u64 => ReFungibleItemType<T::AccountId>;123124 pub AddressTokens get(fn address_tokens): double_map hasher(blake2_128_concat) u64, hasher(blake2_128_concat) T::AccountId => Vec<u64>;125 }126}127128decl_event!(129 pub enum Event<T>130 where131 AccountId = <T as system::Trait>::AccountId,132 {133 Created(u64, u8, AccountId),134 ItemCreated(u64, u64),135 ItemDestroyed(u64, u64),136 }137);138139decl_module! {140 pub struct Module<T: Trait> for enum Call where origin: T::Origin {141142 fn deposit_event() = default;143144 // Create collection of NFT with given parameters145 //146 // @param customDataSz size of custom data in each collection item147 // returns collection ID148 #[weight = 0]149 pub fn create_collection( origin,150 collection_name: Vec<u16>,151 collection_description: Vec<u16>,152 token_prefix: Vec<u8>,153 mode: CollectionMode) -> DispatchResult {154155 // Anyone can create a collection156 let who = ensure_signed(origin)?;157 let custom_data_size = match mode {158 CollectionMode::NFT(size) => size,159 _ => 0160 };161162 let decimal_points = match mode {163 CollectionMode::Fungible(points) => points,164 _ => 0165 };166167 // check params168 ensure!(decimal_points < 100, "decimal_points parameter must be lower than 100"); 169170 let mut name = collection_name.to_vec();171 name.push(0);172 ensure!(name.len() <= 64, "Collection name can not be longer than 63 char");173174 let mut description = collection_description.to_vec();175 description.push(0);176 ensure!(name.len() <= 256, "Collection description can not be longer than 255 char");177178 let mut prefix = token_prefix.to_vec();179 prefix.push(0);180 ensure!(prefix.len() <= 16, "Token prefix can not be longer than 15 char");181182 // Generate next collection ID183 let next_id = NextCollectionID::get()184 .checked_add(1)185 .expect("collection id error");186187 NextCollectionID::put(next_id);188189 // Create new collection190 let new_collection = CollectionType {191 owner: who.clone(),192 name: name,193 mode: mode.clone(),194 access: AccessMode::Normal,195 description: description,196 decimal_points: decimal_points,197 token_prefix: prefix,198 next_item_id: next_id,199 offchain_schema: Vec::new(),200 custom_data_size: custom_data_size,201 sponsor: T::AccountId::default(),202 unconfirmed_sponsor: T::AccountId::default(),203 };204205 // Add new collection to map206 <Collection<T>>::insert(next_id, new_collection);207208 // call event209 Self::deposit_event(RawEvent::Created(next_id, mode.into(), who.clone()));210211 Ok(())212 }213214 #[weight = 0]215 pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {216217 let sender = ensure_signed(origin)?;218 Self::check_owner_permissions(collection_id, sender)?;219220 <AddressTokens<T>>::remove_prefix(collection_id);221 <ApprovedList<T>>::remove_prefix(collection_id);222 <Balance<T>>::remove_prefix(collection_id);223 <ItemListIndex>::remove(collection_id);224 <AdminList<T>>::remove(collection_id);225 <Collection<T>>::remove(collection_id);226227 Ok(())228 }229230 #[weight = 0]231 pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {232233 let sender = ensure_signed(origin)?;234 Self::check_owner_permissions(collection_id, sender)?;235 let mut target_collection = <Collection<T>>::get(collection_id);236 target_collection.owner = new_owner;237 <Collection<T>>::insert(collection_id, target_collection);238239 Ok(())240 }241242 #[weight = 0]243 pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {244245 let sender = ensure_signed(origin)?;246 Self::check_owner_or_admin_permissions(collection_id, sender)?;247 let mut admin_arr: Vec<T::AccountId> = Vec::new();248249 if <AdminList<T>>::contains_key(collection_id)250 {251 admin_arr = <AdminList<T>>::get(collection_id);252 ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");253 }254255 admin_arr.push(new_admin_id);256 <AdminList<T>>::insert(collection_id, admin_arr);257258 Ok(())259 }260261 #[weight = 0]262 pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {263264 let sender = ensure_signed(origin)?;265 Self::check_owner_or_admin_permissions(collection_id, sender)?;266267 if <AdminList<T>>::contains_key(collection_id)268 {269 let mut admin_arr = <AdminList<T>>::get(collection_id);270 admin_arr.retain(|i| *i != account_id);271 <AdminList<T>>::insert(collection_id, admin_arr);272 }273274 Ok(())275 }276277 #[weight = 0]278 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {279280 let sender = ensure_signed(origin)?;281282 // check size283 let target_collection = <Collection<T>>::get(collection_id);284 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");285286 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;287288 let new_balance = <Balance<T>>::get(collection_id, owner.clone()) + 1;289 <Balance<T>>::insert(collection_id, owner.clone(), new_balance);290291 // TODO: implement other modes292 match target_collection.mode 293 {294 CollectionMode::NFT(_) => {295 // Create nft item296 let item = NftItemType {297 collection: collection_id,298 owner: owner,299 data: properties,300 };301 302 Self::add_nft_item(item)?;303 304 },305 _ => ()306 };307308 // call event309 Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));310311 Ok(())312 }313314 #[weight = 0]315 pub fn burn_item(origin, collection_id: u64, item_id: u64) -> DispatchResult {316317 let sender = ensure_signed(origin)?;318 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);319 if !item_owner320 {321 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;322 }323 324 Self::burn_nft_item(collection_id, item_id)?;325326 // call event327 Self::deposit_event(RawEvent::ItemDestroyed(collection_id, item_id));328329 Ok(())330 }331332 #[weight = 0]333 pub fn transfer(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, value: u64) -> DispatchResult {334335 let sender = ensure_signed(origin)?;336 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);337 if !item_owner338 {339 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;340 }341342 let target_collection = <Collection<T>>::get(collection_id);343344 // TODO: implement other modes345 match target_collection.mode 346 {347 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, recipient)?,348 _ => ()349 };350351 Ok(())352 }353354 #[weight = 0]355 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {356357 let sender = ensure_signed(origin)?;358359 let item_owner = Self::is_item_owner(sender.clone(), collection_id, item_id);360 if !item_owner361 {362 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;363 }364365 let list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);366 if list_exists {367368 let mut list = <ApprovedList<T>>::get(collection_id, item_id);369 let item_contains = list.contains(&approved.clone());370371 if !item_contains {372 list.push(approved.clone());373 }374 } else {375376 let mut itm = Vec::new();377 itm.push(approved.clone());378 <ApprovedList<T>>::insert(collection_id, item_id, itm);379 }380381 Ok(())382 }383384 #[weight = 0]385 pub fn transfer_from(origin, recipient: T::AccountId, collection_id: u64, item_id: u64, ) -> DispatchResult {386387 let mut approved: bool = false; 388 let sender = ensure_signed(origin)?;389 let approved_list_exists = <ApprovedList<T>>::contains_key(collection_id, item_id);390 if approved_list_exists391 {392 let list_itm = <ApprovedList<T>>::get(collection_id, item_id);393 approved = list_itm.contains(&recipient.clone());394 }395396 if !approved397 {398 Self::check_owner_or_admin_permissions(collection_id, sender)?;399 }400 401 let target_collection = <Collection<T>>::get(collection_id);402403 match target_collection.mode404 {405 CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, recipient)?,406 // TODO: implement other modes407 _ => ()408 };409410 Ok(())411 }412413 #[weight = 0]414 pub fn safe_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 // // on_nft_received call422423 // Self::transfer(origin, collection_id, item_id, new_owner)?;424425 Ok(())426 }427428 #[weight = 0]429 pub fn set_offchain_schema(430 origin,431 collection_id: u64,432 schema: Vec<u8>433 ) -> DispatchResult {434 let sender = ensure_signed(origin)?;435 Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;436 437 let mut target_collection = <Collection<T>>::get(collection_id);438 target_collection.offchain_schema = schema;439 <Collection<T>>::insert(collection_id, target_collection);440441 Ok(()) 442 }443 }444}445446impl<T: Trait> Module<T> {447448 fn collection_exists(collection_id: u64) -> DispatchResult{449 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");450 Ok(())451 }452453 fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {454455 Self::collection_exists(collection_id)?;456457 let target_collection = <Collection<T>>::get(collection_id);458 ensure!(subject == target_collection.owner, "You do not own this collection");459460 Ok(())461 }462463 fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {464465 Self::collection_exists(collection_id)?;466467 let target_collection = <Collection<T>>::get(collection_id);468 let is_owner = subject == target_collection.owner;469470 let no_perm_mes = "You do not have permissions to modify this collection";471 let exists = <AdminList<T>>::contains_key(collection_id);472473 if !is_owner474 {475 ensure!(exists, no_perm_mes);476 ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);477 }478 Ok(())479 }480481 fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{482483 let target_collection = <Collection<T>>::get(collection_id);484485 match target_collection.mode {486 CollectionMode::NFT(_) => <NftItemList<T>>::get(collection_id, item_id).owner == subject,487 CollectionMode::Fungible(_) => <FungibleItemList<T>>::get(collection_id, item_id).owner.contains(&subject),488 CollectionMode::ReFungible => <ReFungibleItemList<T>>::get(collection_id, item_id).owner.iter().any(|i| i.owner == subject),489 CollectionMode::Invalid => false490 }491 }492493 fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {494495 let current_index = <ItemListIndex>::get(item.collection)496 .checked_add(1)497 .expect("Item list index id error");498499 Self::add_token_index(item.collection, current_index, item.owner.clone())?;500501 <ItemListIndex>::insert(item.collection, current_index);502 <NftItemList<T>>::insert(item.collection, current_index, item);503504 Ok(())505 }506507 fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {508 509 let item = <NftItemList<T>>::get(collection_id, item_id);510 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;511512 // update balance513 let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();514 <Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);515 <NftItemList<T>>::remove(collection_id, item_id);516517 Ok(())518 }519520 fn transfer_nft(collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {521522 let mut item = <NftItemList<T>>::get(collection_id, item_id);523524 // update balance525 let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();526 <Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);527528 let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();529 <Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);530531 // change owner532 let old_owner = item.owner.clone();533 item.owner = new_owner.clone();534 <NftItemList<T>>::insert(collection_id, item_id, item);535536 // update index collection537 Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;538539 // reset approved list540 let itm: Vec<T::AccountId> = Vec::new();541 <ApprovedList<T>>::insert(collection_id, item_id, itm);542543 Ok(())544 }545546 fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {547 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());548 if list_exists {549 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());550 let item_contains = list.contains(&item_index.clone());551552 if !item_contains {553 list.push(item_index.clone());554 }555556 <AddressTokens<T>>::insert(collection_id, owner.clone(), list);557 } else {558 let mut itm = Vec::new();559 itm.push(item_index.clone());560 <AddressTokens<T>>::insert(collection_id, owner, itm);561 }562563 Ok(())564 }565566 fn remove_token_index(567 collection_id: u64,568 item_index: u64,569 owner: T::AccountId,570 ) -> DispatchResult {571 let list_exists = <AddressTokens<T>>::contains_key(collection_id, owner.clone());572 if list_exists {573 let mut list = <AddressTokens<T>>::get(collection_id, owner.clone());574 let item_contains = list.contains(&item_index.clone());575576 if item_contains {577 list.retain(|&item| item != item_index);578 <AddressTokens<T>>::insert(collection_id, owner, list);579 }580 }581582 Ok(())583 }584585 fn move_token_index(586 collection_id: u64,587 item_index: u64,588 old_owner: T::AccountId,589 new_owner: T::AccountId,590 ) -> DispatchResult {591 Self::remove_token_index(collection_id, item_index, old_owner)?;592 Self::add_token_index(collection_id, item_index, new_owner)?;593594 Ok(())595 }596}smart_contract/ink-types-node-runtime/README.mddiffbeforeafterboth--- a/smart_contract/ink-types-node-runtime/README.md
+++ b/smart_contract/ink-types-node-runtime/README.md
@@ -30,4 +30,67 @@
## Test
```
cargo +nightly test
+```
+
+## UI custom types
+```
+{
+ "Schedule": {
+ "version": "u32",
+ "put_code_per_byte_cost": "Gas",
+ "grow_mem_cost": "Gas",
+ "regular_op_cost": "Gas",
+ "return_data_per_byte_cost": "Gas",
+ "event_data_per_byte_cost": "Gas",
+ "event_per_topic_cost": "Gas",
+ "event_base_cost": "Gas",
+ "call_base_cost": "Gas",
+ "instantiate_base_cost": "Gas",
+ "dispatch_base_cost": "Gas",
+ "sandbox_data_read_cost": "Gas",
+ "sandbox_data_write_cost": "Gas",
+ "transfer_cost": "Gas",
+ "instantiate_cost": "Gas",
+ "max_event_topics": "u32",
+ "max_stack_height": "u32",
+ "max_memory_pages": "u32",
+ "max_table_size": "u32",
+ "enable_println": "bool",
+ "max_subject_len": "u32"
+ },
+ "CollectionMode": {
+ "_enum": {
+ "Invalid": null,
+ "NFT": "u32",
+ "Fungible": "u32",
+ "ReFungible": null
+ }
+ },
+ "NftItemType": {
+ "Collection": "u64",
+ "Owner": "AccountId",
+ "Data": "Vec<u8>"
+ },
+
+
+"CollectionType": {
+ "Owner": "AccountId",
+ "Mode": "u8",
+ "ModeParam": "u32",
+ "Access": "u8",
+ "NextItemId": "u64",
+ "DecimalPoints": "u32",
+ "Name": "Vec<u16>",
+ "Description": "Vec<u16>",
+ "TokenPrefix": "Vec<u8>",
+ "CustomDataSize": "u32",
+ "OffchainSchema": "Vec<u8>",
+ "Sponsor": "AccountId",
+ "UnconfirmedSponsor": "AccountId"
+ },
+ "RawData": "Vec<u8>",
+ "Address": "AccountId",
+ "LookupSource": "AccountId",
+ "Weight": "u64"
+}
```
\ No newline at end of file
smart_contract/ink-types-node-runtime/calls/lib.rsdiffbeforeafterboth--- a/smart_contract/ink-types-node-runtime/calls/lib.rs
+++ b/smart_contract/ink-types-node-runtime/calls/lib.rs
@@ -123,15 +123,14 @@
}
// SafeTransferFrom
-
#[ink(message)]
- fn create_item(&self, collection_id: u64, properties: Vec<u8>) {
+ fn create_item(&self, collection_id: u64, properties: Vec<u8>, owner: AccountId) {
env::println(&format!(
"create_item invoke_runtime params {:?}, {:?} ",
collection_id, properties
));
- let create_item_call = runtime_calls::create_item(collection_id, properties);
+ let create_item_call = runtime_calls::create_item(collection_id, properties, owner);
// dispatch the call to the runtime
let result = self.env().invoke_runtime(&create_item_call);
smart_contract/ink-types-node-runtime/src/calls.rsdiffbeforeafterboth--- a/smart_contract/ink-types-node-runtime/src/calls.rs
+++ b/smart_contract/ink-types-node-runtime/src/calls.rs
@@ -25,7 +25,7 @@
T::AccountId: Member + Codec,
{
#[allow(non_camel_case_types)]
- create_collection(Vec<u16>, Vec<u16>, Vec<u8>, u32),
+ create_collection(Vec<u16>, Vec<u16>, Vec<u8>, u8, u32, u32),
#[allow(non_camel_case_types)]
destroy_collection(u64),
@@ -40,19 +40,19 @@
remove_collection_admin(u64, T::AccountId),
#[allow(non_camel_case_types)]
- create_item(u64, Vec<u8>),
+ create_item(u64, Vec<u8>, T::AccountId),
#[allow(non_camel_case_types)]
burn_item(u64, u64),
#[allow(non_camel_case_types)]
- transfer(u64, u64, T::AccountId),
+ transfer(T::AccountId, u64, u64),
#[allow(non_camel_case_types)]
nft_approve(T::AccountId, u64, u64),
#[allow(non_camel_case_types)]
- nft_transfer_from(u64, u64, T::AccountId),
+ nft_transfer_from(T::AccountId, u64, u64),
#[allow(non_camel_case_types)]
nft_safe_transfer(u64, u64, T::AccountId),
@@ -66,13 +66,17 @@
collection_name: Vec<u16>,
collection_description: Vec<u16>,
token_prefix: Vec<u8>,
- custom_data_sz: u32,
+ mode: u8,
+ decimal_points: u32,
+ custom_data_size: u32,
) -> Call {
Nft::<NodeRuntimeTypes>::create_collection(
collection_name,
collection_description,
token_prefix,
- custom_data_sz,
+ mode,
+ decimal_points,
+ custom_data_size,
)
.into()
}
@@ -89,8 +93,8 @@
Nft::<NodeRuntimeTypes>::nft_transfer_from(collection_id, item_id, new_owner.into()).into()
}
-pub fn create_item(collection_id: u64, properties: Vec<u8>) -> Call {
- Nft::<NodeRuntimeTypes>::create_item(collection_id, properties).into()
+pub fn create_item(collection_id: u64, properties: Vec<u8>, owner: AccountId) -> Call {
+ Nft::<NodeRuntimeTypes>::create_item(collection_id, properties, owner).into()
}
pub fn burn_item(collection_id: u64, item_id: u64) -> Call {