difftreelog
NFTPAR-47 + contracts module
in: master
9 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2762,8 +2762,10 @@
version = "2.0.0-rc4"
dependencies = [
"futures 0.3.5",
+ "jsonrpc-core",
"log",
"nft-runtime",
+ "pallet-contracts-rpc",
"parking_lot 0.10.2",
"sc-basic-authorship",
"sc-cli",
@@ -2773,6 +2775,7 @@
"sc-executor",
"sc-finality-grandpa",
"sc-network",
+ "sc-rpc",
"sc-service",
"sc-transaction-pool",
"sp-consensus",
@@ -2795,6 +2798,9 @@
"frame-system",
"pallet-aura",
"pallet-balances",
+ "pallet-contracts",
+ "pallet-contracts-primitives",
+ "pallet-contracts-rpc-runtime-api",
"pallet-grandpa",
"pallet-nft",
"pallet-randomness-collective-flip",
@@ -3013,6 +3019,67 @@
]
[[package]]
+name = "pallet-contracts"
+version = "2.0.0-rc4"
+source = "git+https://github.com/paritytech/substrate.git?tag=v2.0.0-rc4#00768a1f21a579c478fe5d4f51e1fa71f7db9fd4"
+dependencies = [
+ "frame-support",
+ "frame-system",
+ "pallet-contracts-primitives",
+ "parity-scale-codec",
+ "parity-wasm",
+ "pwasm-utils",
+ "serde",
+ "sp-core",
+ "sp-io",
+ "sp-runtime",
+ "sp-sandbox",
+ "sp-std",
+ "wasmi-validation",
+]
+
+[[package]]
+name = "pallet-contracts-primitives"
+version = "2.0.0-rc4"
+source = "git+https://github.com/paritytech/substrate.git?tag=v2.0.0-rc4#00768a1f21a579c478fe5d4f51e1fa71f7db9fd4"
+dependencies = [
+ "parity-scale-codec",
+ "sp-runtime",
+ "sp-std",
+]
+
+[[package]]
+name = "pallet-contracts-rpc"
+version = "0.8.0-rc4"
+source = "git+https://github.com/paritytech/substrate.git?tag=v2.0.0-rc4#00768a1f21a579c478fe5d4f51e1fa71f7db9fd4"
+dependencies = [
+ "jsonrpc-core",
+ "jsonrpc-core-client",
+ "jsonrpc-derive",
+ "pallet-contracts-primitives",
+ "pallet-contracts-rpc-runtime-api",
+ "parity-scale-codec",
+ "serde",
+ "sp-api",
+ "sp-blockchain",
+ "sp-core",
+ "sp-rpc",
+ "sp-runtime",
+]
+
+[[package]]
+name = "pallet-contracts-rpc-runtime-api"
+version = "0.8.0-rc4"
+source = "git+https://github.com/paritytech/substrate.git?tag=v2.0.0-rc4#00768a1f21a579c478fe5d4f51e1fa71f7db9fd4"
+dependencies = [
+ "pallet-contracts-primitives",
+ "parity-scale-codec",
+ "sp-api",
+ "sp-runtime",
+ "sp-std",
+]
+
+[[package]]
name = "pallet-finality-tracker"
version = "2.0.0-rc4"
source = "git+https://github.com/paritytech/substrate.git?tag=v2.0.0-rc4#00768a1f21a579c478fe5d4f51e1fa71f7db9fd4"
@@ -3620,6 +3687,17 @@
checksum = "8e86d370532557ae7573551a1ec8235a0f8d6cb276c7c9e6aa490b511c447485"
[[package]]
+name = "pwasm-utils"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4f7a12f176deee919f4ba55326ee17491c8b707d0987aed822682c821b660192"
+dependencies = [
+ "byteorder",
+ "log",
+ "parity-wasm",
+]
+
+[[package]]
name = "quick-error"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -5576,6 +5654,19 @@
]
[[package]]
+name = "sp-sandbox"
+version = "0.8.0-rc4"
+source = "git+https://github.com/paritytech/substrate.git?tag=v2.0.0-rc4#00768a1f21a579c478fe5d4f51e1fa71f7db9fd4"
+dependencies = [
+ "parity-scale-codec",
+ "sp-core",
+ "sp-io",
+ "sp-std",
+ "sp-wasm-interface",
+ "wasmi",
+]
+
+[[package]]
name = "sp-serializer"
version = "2.0.0-rc4"
source = "git+https://github.com/paritytech/substrate.git?tag=v2.0.0-rc4#00768a1f21a579c478fe5d4f51e1fa71f7db9fd4"
node/Cargo.tomldiffbeforeafterboth--- a/node/Cargo.toml
+++ b/node/Cargo.toml
@@ -20,6 +20,16 @@
log = '0.4.8'
parking_lot = '0.10.0'
structopt = '0.3.8'
+jsonrpc-core = '14.0.5'
+
+[dependencies.pallet-contracts-rpc]
+git = 'https://github.com/paritytech/substrate.git'
+version = '0.8.0-rc4'
+tag = 'v2.0.0-rc4'
+
+[dependencies.sc-rpc]
+git = 'https://github.com/paritytech/substrate.git'
+tag = 'v2.0.0-rc4'
[dependencies.nft-runtime]
path = '../runtime'
node/src/chain_spec.rsdiffbeforeafterboth--- a/node/src/chain_spec.rs
+++ b/node/src/chain_spec.rs
@@ -8,6 +8,8 @@
use sp_runtime::traits::{Verify, IdentifyAccount};
use sc_service::ChainType;
+use nft_runtime::{ContractsConfig, ContractsSchedule};
+
// Note this is the URL for the telemetry server
//const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";
@@ -111,6 +113,12 @@
balances: Some(BalancesConfig {
balances: endowed_accounts.iter().cloned().map(|k|(k, 1 << 60)).collect(),
}),
+ contracts: Some(ContractsConfig {
+ current_schedule: ContractsSchedule {
+ // enable_println,
+ ..Default::default()
+ },
+ }),
aura: Some(AuraConfig {
authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(),
}),
node/src/service.rsdiffbeforeafterboth--- a/node/src/service.rs
+++ b/node/src/service.rs
@@ -27,6 +27,7 @@
/// be able to perform chain operations.
macro_rules! new_full_start {
($config:expr) => {{
+ use jsonrpc_core::IoHandler;
use std::sync::Arc;
use sp_consensus_aura::sr25519::AuthorityPair as AuraPair;
@@ -86,7 +87,15 @@
import_setup = Some((grandpa_block_import, grandpa_link));
Ok(import_queue)
- })?;
+ })?
+ .with_rpc_extensions(|builder| -> Result<IoHandler<sc_rpc::Metadata>, _> {
+ let handler = pallet_contracts_rpc::Contracts::new(builder.client().clone());
+ let delegate = pallet_contracts_rpc::ContractsApi::to_delegate(handler);
+
+ let mut io = IoHandler::default();
+ io.extend_with(delegate);
+ Ok(io)
+ })?;
(builder, import_setup, inherent_data_providers)
}}
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 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 pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;63 //pub Collection get(collection): map hasher(identity) u64 => CollectionType<T::AccountId>;6465 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 ItemList get(item_id): map hasher(blake2_128_concat) (u64, u64) => NftItemType<T::AccountId>;7374 pub ItemListIndex get(fn item_index): map hasher(blake2_128_concat) u64 => u64;75 // pub ItemListIndex get(item_index): map hasher(blake2_128_concat) u64 => u64;76 }77}7879// The pallet's events80decl_event!(81 pub enum Event<T>82 where83 AccountId = <T as system::Trait>::AccountId,84 {85 Created(u32, AccountId),86 }87);8889// The pallet's dispatchable functions.90decl_module! {91 /// The module declaration.92 pub struct Module<T: Trait> for enum Call where origin: T::Origin {9394 // Initializing events95 // this is needed only if you are using events in your pallet96 fn deposit_event() = default;9798 // Initializing events99 // this is needed only if you are using events in your module100 // fn deposit_event<T>() = default;101102 // Create collection of NFT with given parameters103 //104 // @param customDataSz size of custom data in each collection item105 // returns collection ID106107 // Create collection of NFT with given parameters108 //109 // @param customDataSz size of custom data in each collection item110 // returns collection ID111 #[weight = 0]112 pub fn create_collection(origin, custom_data_sz: u32) -> DispatchResult {113 // Anyone can create a collection114 let who = ensure_signed(origin)?;115116 // Generate next collection ID117 let next_id = NextCollectionID::get();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 = 0]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 = 0]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 = 0]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 = 0]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 = 0]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);251 <ItemListIndex>::insert(collection_id, current_index);252 <ItemList<T>>::insert((collection_id, current_index), new_item);253254 Ok(())255 }256257 #[weight = 0]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 = 0]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 = 0]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 = 0]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 }387388 #[weight = 0]389 pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {390391 let no_perm_mes = "You do not have permissions to modify this collection";392 ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);393 let list_itm = <ApprovedList<T>>::get((collection_id, item_id));394 ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);395396 // on_nft_received call397398 Self::transfer(origin, collection_id, item_id, new_owner)?;399400 Ok(())401 }402 }403}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;61 pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;62 pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;6364 /// Balance owner per collection map65 pub Balance get(fn balance_count): map hasher(blake2_128_concat) (u64, T::AccountId) => u64;66 pub ApprovedList get(fn approved): map hasher(blake2_128_concat) (u64, u64) => Vec<T::AccountId>;6768 pub ItemList get(fn item_id): map hasher(blake2_128_concat) (u64, u64) => NftItemType<T::AccountId>;69 pub ItemListIndex get(fn item_index): map hasher(blake2_128_concat) u64 => u64;7071 pub AddressTokens get(fn address_tokens): map hasher(blake2_128_concat) (u64, T::AccountId) => Vec<u64>;7273 }74}7576// The pallet's events77decl_event!(78 pub enum Event<T>79 where80 AccountId = <T as system::Trait>::AccountId,81 {82 Created(u32, AccountId),83 }84);8586// The pallet's dispatchable functions.87decl_module! {88 /// The module declaration.89 pub struct Module<T: Trait> for enum Call where origin: T::Origin {9091 // Initializing events92 // this is needed only if you are using events in your pallet93 fn deposit_event() = default;9495 // Initializing events96 // this is needed only if you are using events in your module97 // fn deposit_event<T>() = default;9899 // Create collection of NFT with given parameters100 //101 // @param customDataSz size of custom data in each collection item102 // returns collection ID103104 // Create collection of NFT with given parameters105 //106 // @param customDataSz size of custom data in each collection item107 // returns collection ID108 #[weight = 0]109 pub fn create_collection(origin, custom_data_sz: u32) -> DispatchResult {110 // Anyone can create a collection111 let who = ensure_signed(origin)?;112113 // Generate next collection ID114 let next_id = NextCollectionID::get();115116 NextCollectionID::put(next_id);117118 // Create new collection119 let new_collection = CollectionType {120 owner: who,121 next_item_id: next_id,122 custom_data_size: custom_data_sz,123 };124125 // Add new collection to map126 <Collection<T>>::insert(next_id, new_collection);127128 Ok(())129 }130131 #[weight = 0]132 pub fn destroy_collection(origin, collection_id: u64) -> DispatchResult {133134 let sender = ensure_signed(origin)?;135 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");136137 let owner = <Collection<T>>::get(collection_id).owner;138 ensure!(sender == owner, "You do not own this collection");139 <Collection<T>>::remove(collection_id);140141 Ok(())142 }143144 #[weight = 0]145 pub fn change_collection_owner(origin, collection_id: u64, new_owner: T::AccountId) -> DispatchResult {146147 let sender = ensure_signed(origin)?;148 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");149150 let mut target_collection = <Collection<T>>::get(collection_id);151 ensure!(sender == target_collection.owner, "You do not own this collection");152153 target_collection.owner = new_owner;154 <Collection<T>>::insert(collection_id, target_collection);155156 Ok(())157 }158159 #[weight = 0]160 pub fn add_collection_admin(origin, collection_id: u64, new_admin_id: T::AccountId) -> DispatchResult {161162 let sender = ensure_signed(origin)?;163 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");164165 let target_collection = <Collection<T>>::get(collection_id);166 let is_owner = sender == target_collection.owner;167168 let no_perm_mes = "You do not have permissions to modify this collection";169 let exists = <AdminList<T>>::contains_key(collection_id);170171 if !is_owner172 {173 ensure!(exists, no_perm_mes);174 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);175 }176177 let mut admin_arr: Vec<T::AccountId> = Vec::new();178 if exists179 {180 admin_arr = <AdminList<T>>::get(collection_id);181 ensure!(!admin_arr.contains(&new_admin_id), "Account already has admin role");182 }183184 admin_arr.push(new_admin_id);185 <AdminList<T>>::insert(collection_id, admin_arr);186187 Ok(())188 }189190 #[weight = 0]191 pub fn remove_collection_admin(origin, collection_id: u64, account_id: T::AccountId) -> DispatchResult {192193 let sender = ensure_signed(origin)?;194 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");195196 let target_collection = <Collection<T>>::get(collection_id);197 let is_owner = sender == target_collection.owner;198199 let no_perm_mes = "You do not have permissions to modify this collection";200 let exists = <AdminList<T>>::contains_key(collection_id);201202 if !is_owner203 {204 ensure!(exists, no_perm_mes);205 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);206 }207208 if exists209 {210 let mut admin_arr = <AdminList<T>>::get(collection_id);211 admin_arr.retain(|i| *i != account_id);212 <AdminList<T>>::insert(collection_id, admin_arr);213 }214215 Ok(())216 }217218 #[weight = 0]219 pub fn create_item(origin, collection_id: u64, properties: Vec<u8>) -> DispatchResult {220221 let sender = ensure_signed(origin)?;222 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");223224 let target_collection = <Collection<T>>::get(collection_id);225 ensure!(target_collection.custom_data_size >= properties.len() as u32, "Size of item is too large");226 let is_owner = sender == target_collection.owner;227228 let no_perm_mes = "You do not have permissions to modify this collection";229 let exists = <AdminList<T>>::contains_key(collection_id);230231 if !is_owner232 {233 ensure!(exists, no_perm_mes);234 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);235 }236237 let new_balance = <Balance<T>>::get((collection_id, sender.clone())) + 1;238 <Balance<T>>::insert((collection_id, sender.clone()), new_balance);239240 // Create new item241 let new_item = NftItemType {242 collection: collection_id,243 owner: sender,244 data: properties,245 };246247248 let current_index = <ItemListIndex>::get(collection_id);249250 Self::add_token_index(collection_id, current_index, new_item.owner.clone())?;251252 <ItemListIndex>::insert(collection_id, current_index);253 <ItemList<T>>::insert((collection_id, current_index), new_item);254255 Ok(())256 }257258 #[weight = 0]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_owner271 {272 // check if item owner273 if item.owner != sender274 {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 Self::remove_token_index(collection_id, item_id, item.owner.clone())?;284285 // update balance286 let new_balance = <Balance<T>>::get((collection_id, item.owner.clone())) - 1;287 <Balance<T>>::insert((collection_id, item.owner.clone()), new_balance);288289 Ok(())290 }291292 #[weight = 0]293 pub fn transfer(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {294295 let sender = ensure_signed(origin)?;296 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");297298 let target_collection = <Collection<T>>::get(collection_id);299 let is_owner = sender == target_collection.owner;300301 ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");302 let mut item = <ItemList<T>>::get((collection_id, item_id));303304 if !is_owner305 {306 // check if item owner307 if item.owner != sender308 {309 let no_perm_mes = "You do not have permissions to modify this collection";310311 ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);312 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);313 }314 }315 <ItemList<T>>::remove((collection_id, item_id));316317 // update balance318 let balance_old_owner = <Balance<T>>::get((collection_id, item.owner.clone())) - 1;319 <Balance<T>>::insert((collection_id, item.owner.clone()), balance_old_owner);320321 let balance_new_owner = <Balance<T>>::get((collection_id, new_owner.clone())) + 1;322 <Balance<T>>::insert((collection_id, new_owner.clone()), balance_new_owner);323324 // change owner325 let old_owner = item.owner.clone();326 item.owner = new_owner.clone();327 <ItemList<T>>::insert((collection_id, item_id), item);328329 // update index collection330 Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;331332 // reset approved list333 let itm: Vec<T::AccountId> = Vec::new();334 <ApprovedList<T>>::insert((collection_id, item_id), itm);335336 Ok(())337 }338339 #[weight = 0]340 pub fn approve(origin, approved: T::AccountId, collection_id: u64, item_id: u64) -> DispatchResult {341342 let sender = ensure_signed(origin)?;343 ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");344345 let target_collection = <Collection<T>>::get(collection_id);346 let is_owner = sender == target_collection.owner;347348 ensure!(<ItemList<T>>::contains_key((collection_id, item_id)), "Item does not exists");349 let item = <ItemList<T>>::get((collection_id, item_id));350351 if !is_owner352 {353 // check if item owner354 if item.owner != sender355 {356 let no_perm_mes = "You do not have permissions to modify this collection";357358 ensure!(<AdminList<T>>::contains_key(collection_id), no_perm_mes);359 ensure!(<AdminList<T>>::get(collection_id).contains(&sender), no_perm_mes);360 }361 }362363 let list_exists = <ApprovedList<T>>::contains_key((collection_id, item_id));364 if list_exists {365366 let mut list = <ApprovedList<T>>::get((collection_id, item_id));367 let item_contains = list.contains(&approved.clone());368369 if !item_contains {370 list.push(approved.clone());371 }372 } else {373374 let mut itm = Vec::new();375 itm.push(approved.clone());376 <ApprovedList<T>>::insert((collection_id, item_id), itm);377 }378379 Ok(())380 }381382 #[weight = 0]383 pub fn transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {384385 let no_perm_mes = "You do not have permissions to modify this collection";386 ensure!(<ApprovedList<T>>::contains_key((collection_id, item_id)), no_perm_mes);387 let list_itm = <ApprovedList<T>>::get((collection_id, item_id));388 ensure!(list_itm.contains(&new_owner.clone()), no_perm_mes);389390 Self::transfer(origin, collection_id, item_id, new_owner)?;391392 Ok(())393 }394395 #[weight = 0]396 pub fn safe_transfer_from(origin, collection_id: u64, item_id: u64, new_owner: T::AccountId) -> DispatchResult {397398 let no_perm_mes = "You do not have permissions to modify this collection";399 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 // on_nft_received call404405 Self::transfer(origin, collection_id, item_id, new_owner)?;406407 Ok(())408 }409 }410}411412413impl<T: Trait> Module<T> {414 fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {415 416 let list_exists = <AddressTokens<T>>::contains_key((collection_id, owner.clone()));417 if list_exists {418419 let mut list = <AddressTokens<T>>::get((collection_id, owner.clone()));420 let item_contains = list.contains(&item_index.clone());421422 if !item_contains {423 list.push(item_index.clone());424 }425426 <AddressTokens<T>>::insert((collection_id, owner.clone()), list);427428 } else {429430 let mut itm = Vec::new();431 itm.push(item_index.clone());432 <AddressTokens<T>>::insert((collection_id, owner), itm);433 }434435 Ok(())436 }437438 fn remove_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {439 440 let list_exists = <AddressTokens<T>>::contains_key((collection_id, owner.clone()));441 if list_exists {442443 let mut list = <AddressTokens<T>>::get((collection_id, owner.clone()));444 let item_contains = list.contains(&item_index.clone());445446 if item_contains {447 list.retain(|&item| item != item_index);448 <AddressTokens<T>>::insert((collection_id, owner), list);449 }450 }451452 Ok(())453 }454455 fn move_token_index(collection_id: u64, item_index: u64, old_owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {456 457 Self::remove_token_index(collection_id, item_index, old_owner)?;458 Self::add_token_index(collection_id, item_index, new_owner)?;459 460 Ok(())461 }462}pallets/nft/src/mock.rsdiffbeforeafterboth--- a/pallets/nft/src/mock.rs
+++ b/pallets/nft/src/mock.rs
@@ -1,7 +1,12 @@
// Creating mock runtime here
use crate::{Module, Trait};
-use frame_support::{impl_outer_origin, parameter_types, weights::Weight};
+use frame_support::{
+ impl_outer_origin, parameter_types,
+ weights::{
+ Weight,
+ constants::{ BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND },
+ }};
use frame_system as system;
use sp_core::H256;
use sp_runtime::{
@@ -11,7 +16,8 @@
};
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
@@ -24,12 +30,17 @@
pub const MaximumBlockWeight: Weight = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);
+ pub MaximumExtrinsicWeight: Weight = 10 * WEIGHT_PER_SECOND;
}
+
impl system::Trait for Test {
type Origin = Origin;
type Call = ();
type Index = u64;
type BlockNumber = u64;
+ type BaseCallFilter = ();
+ type DbWeight = RocksDbWeight;
+ type BlockExecutionWeight = BlockExecutionWeight;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = u64;
@@ -37,6 +48,8 @@
type Header = Header;
type Event = ();
type BlockHashCount = BlockHashCount;
+ type ExtrinsicBaseWeight = ExtrinsicBaseWeight;
+ type MaximumExtrinsicWeight = MaximumExtrinsicWeight;
type MaximumBlockWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
@@ -49,6 +62,7 @@
impl Trait for Test {
type Event = ();
}
+
pub type TemplateModule = Module<Test>;
// This function basically just builds a genesis storage key/value store according to
pallets/nft/src/tests.rsdiffbeforeafterboth--- a/pallets/nft/src/tests.rs
+++ b/pallets/nft/src/tests.rs
@@ -297,3 +297,50 @@
assert_ok!(TemplateModule::transfer_from(origin1.clone(), 1, 1, 2));
});
}
+
+#[test]
+fn index_list() {
+ new_test_ext().execute_with(|| {
+ let size = 1024;
+ let origin1 = Origin::signed(1);
+ let origin2 = Origin::signed(2);
+ let origin3 = Origin::signed(3);
+
+ assert_ok!(TemplateModule::create_collection(origin1.clone(), size));
+ assert_ok!(TemplateModule::create_collection(origin2.clone(), size));
+ assert_ok!(TemplateModule::create_collection(origin3.clone(), size));
+
+ assert_eq!(TemplateModule::collection(1).owner, 1);
+ assert_eq!(TemplateModule::collection(2).owner, 2);
+ assert_eq!(TemplateModule::collection(3).owner, 3);
+
+ // create items
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 1, 1].to_vec()
+ ));
+
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 1, 2].to_vec()
+ ));
+
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 2, 3].to_vec()
+ ));
+
+ assert_eq!(TemplateModule::address_tokens((1, 1)).len(), 3);
+
+ // burn one
+ assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 2));
+ assert_eq!(TemplateModule::address_tokens((1, 1)).len(), 2);
+
+ // burn another one
+ assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 3));
+ assert_eq!(TemplateModule::address_tokens((1, 1))[0], 1);
+ });
+}
\ No newline at end of file
runtime/Cargo.tomldiffbeforeafterboth--- a/runtime/Cargo.toml
+++ b/runtime/Cargo.toml
@@ -4,6 +4,9 @@
'aura/std',
'balances/std',
'codec/std',
+ 'contracts/std',
+ 'contracts-primitives/std',
+ 'contracts-rpc-runtime-api/std',
'frame-executive/std',
'frame-support/std',
'grandpa/std',
@@ -47,6 +50,27 @@
package = 'parity-scale-codec'
version = '1.3.1'
+[dependencies.contracts]
+git = 'https://github.com/paritytech/substrate.git'
+default-features = false
+package = 'pallet-contracts'
+tag = 'v2.0.0-rc4'
+version = '2.0.0-rc4'
+
+[dependencies.contracts-primitives]
+git = 'https://github.com/paritytech/substrate.git'
+default-features = false
+package = 'pallet-contracts-primitives'
+tag = 'v2.0.0-rc4'
+version = '2.0.0-rc4'
+
+[dependencies.contracts-rpc-runtime-api]
+git = 'https://github.com/paritytech/substrate.git'
+default-features = false
+package = 'pallet-contracts-rpc-runtime-api'
+version = '0.8.0-rc4'
+tag = 'v2.0.0-rc4'
+
[dependencies.frame-executive]
default-features = false
git = 'https://github.com/paritytech/substrate.git'
runtime/src/lib.rsdiffbeforeafterboth--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -24,6 +24,7 @@
use sp_version::RuntimeVersion;
#[cfg(feature = "std")]
use sp_version::NativeVersion;
+use contracts_rpc_runtime_api::ContractExecResult;
// A few exports that help ease life for downstream crates.
#[cfg(any(feature = "std", test))]
@@ -31,6 +32,7 @@
pub use timestamp::Call as TimestampCall;
pub use balances::Call as BalancesCall;
pub use sp_runtime::{Permill, Perbill};
+pub use contracts::Schedule as ContractsSchedule;
pub use frame_support::{
construct_runtime, parameter_types, StorageValue,
traits::{KeyOwnerProofSystem, Randomness},
@@ -69,6 +71,10 @@
/// Digest item type.
pub type DigestItem = generic::DigestItem<Hash>;
+pub const MILLICENTS: Balance = 1_000_000_000;
+pub const CENTS: Balance = 1_000 * MILLICENTS;
+pub const DOLLARS: Balance = 100 * CENTS;
+
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
@@ -254,6 +260,32 @@
type Call = Call;
}
+parameter_types! {
+ pub const TombstoneDeposit: Balance = 16 * MILLICENTS;
+ pub const RentByteFee: Balance = 4 * MILLICENTS;
+ pub const RentDepositOffset: Balance = 1000 * MILLICENTS;
+ pub const SurchargeReward: Balance = 150 * MILLICENTS;
+}
+
+impl contracts::Trait for Runtime {
+ type Time = Timestamp;
+ type Randomness = RandomnessCollectiveFlip;
+ type Currency = Balances;
+ type Event = Event;
+ type DetermineContractAddress = contracts::SimpleAddressDeterminer<Runtime>;
+ type TrieIdGenerator = contracts::TrieIdFromParentCounter<Runtime>;
+ type RentPayment = ();
+ type SignedClaimHandicap = contracts::DefaultSignedClaimHandicap;
+ type TombstoneDeposit = TombstoneDeposit;
+ type StorageSizeOffset = contracts::DefaultStorageSizeOffset;
+ type RentByteFee = RentByteFee;
+ type RentDepositOffset = RentDepositOffset;
+ type SurchargeReward = SurchargeReward;
+ type MaxDepth = contracts::DefaultMaxDepth;
+ type MaxValueSize = contracts::DefaultMaxValueSize;
+ type WeightPrice = transaction_payment::Module<Self>;
+}
+
/// Used for the module template in `./template.rs`
impl nft::Trait for Runtime {
type Event = Event;
@@ -267,6 +299,7 @@
{
System: system::{Module, Call, Config, Storage, Event<T>},
RandomnessCollectiveFlip: randomness_collective_flip::{Module, Call, Storage},
+ Contracts: contracts::{Module, Call, Config, Storage, Event<T>},
Timestamp: timestamp::{Module, Call, Storage, Inherent},
Aura: aura::{Module, Config<T>, Inherent(Timestamp)},
Grandpa: grandpa::{Module, Call, Storage, Config, Event},
@@ -413,4 +446,40 @@
None
}
}
+
+ impl contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>
+ for Runtime
+ {
+ fn call(
+ origin: AccountId,
+ dest: AccountId,
+ value: Balance,
+ gas_limit: u64,
+ input_data: Vec<u8>,
+ ) -> ContractExecResult {
+ let exec_result =
+ Contracts::bare_call(origin, dest.into(), value, gas_limit, input_data);
+ match exec_result {
+ Ok(v) => ContractExecResult::Success {
+ status: v.status,
+ data: v.data,
+ },
+ Err(_) => ContractExecResult::Error,
+ }
+ }
+
+ fn get_storage(
+ address: AccountId,
+ key: [u8; 32],
+ ) -> contracts_primitives::GetStorageResult {
+ Contracts::get_storage(address, key)
+ }
+
+ fn rent_projection(
+ address: AccountId,
+ ) -> contracts_primitives::RentProjectionResult<BlockNumber> {
+ Contracts::rent_projection(address)
+ }
+ }
+
}