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.rsdiffbeforeafterboth1//! Service and ServiceFactory implementation. Specialized wrapper over substrate service.23use std::sync::Arc;4use std::time::Duration;5use sc_client_api::ExecutorProvider;6use sc_consensus::LongestChain;7use nft_runtime::{self, opaque::Block, RuntimeApi};8use sc_service::{error::{Error as ServiceError}, AbstractService, Configuration, ServiceBuilder};9use sp_inherents::InherentDataProviders;10use sc_executor::native_executor_instance;11pub use sc_executor::NativeExecutor;12use sp_consensus_aura::sr25519::{AuthorityPair as AuraPair};13use sc_finality_grandpa::{14 FinalityProofProvider as GrandpaFinalityProofProvider, StorageAndProofProvider, SharedVoterState,15};1617// Our native executor instance.18native_executor_instance!(19 pub Executor,20 nft_runtime::api::dispatch,21 nft_runtime::native_version,22);2324/// Starts a `ServiceBuilder` for a full service.25///26/// Use this macro if you don't actually need the full service, but just the builder in order to27/// be able to perform chain operations.28macro_rules! new_full_start {29 ($config:expr) => {{30 use std::sync::Arc;31 use sp_consensus_aura::sr25519::AuthorityPair as AuraPair;3233 let mut import_setup = None;34 let inherent_data_providers = sp_inherents::InherentDataProviders::new();3536 let builder = sc_service::ServiceBuilder::new_full::<37 nft_runtime::opaque::Block,38 nft_runtime::RuntimeApi,39 crate::service::Executor40 >($config)?41 .with_select_chain(|_config, backend| {42 Ok(sc_consensus::LongestChain::new(backend.clone()))43 })?44 .with_transaction_pool(|builder| {45 let pool_api = sc_transaction_pool::FullChainApi::new(46 builder.client().clone(),47 );48 Ok(sc_transaction_pool::BasicPool::new(49 builder.config().transaction_pool.clone(),50 std::sync::Arc::new(pool_api),51 builder.prometheus_registry(),52 ))53 })?54 .with_import_queue(|55 _config,56 client,57 mut select_chain,58 _transaction_pool,59 spawn_task_handle,60 registry,61 | {62 let select_chain = select_chain.take()63 .ok_or_else(|| sc_service::Error::SelectChainRequired)?;6465 let (grandpa_block_import, grandpa_link) = sc_finality_grandpa::block_import(66 client.clone(),67 &(client.clone() as Arc<_>),68 select_chain,69 )?;7071 let aura_block_import = sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new(72 grandpa_block_import.clone(), client.clone(),73 );7475 let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _>(76 sc_consensus_aura::slot_duration(&*client)?,77 aura_block_import,78 Some(Box::new(grandpa_block_import.clone())),79 None,80 client,81 inherent_data_providers.clone(),82 spawn_task_handle,83 registry,84 )?;8586 import_setup = Some((grandpa_block_import, grandpa_link));8788 Ok(import_queue)89 })?;9091 (builder, import_setup, inherent_data_providers)92 }}93}9495/// Builds a new service for a full client.96pub fn new_full(config: Configuration) -> Result<impl AbstractService, ServiceError> {97 let role = config.role.clone();98 let force_authoring = config.force_authoring;99 let name = config.network.node_name.clone();100 let disable_grandpa = config.disable_grandpa;101102 let (builder, mut import_setup, inherent_data_providers) = new_full_start!(config);103104 let (block_import, grandpa_link) =105 import_setup.take()106 .expect("Link Half and Block Import are present for Full Services or setup failed before. qed");107108 let service = builder109 .with_finality_proof_provider(|client, backend| {110 // GenesisAuthoritySetProvider is implemented for StorageAndProofProvider111 let provider = client as Arc<dyn StorageAndProofProvider<_, _>>;112 Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, provider)) as _)113 })?114 .build_full()?;115116 if role.is_authority() {117 let proposer = sc_basic_authorship::ProposerFactory::new(118 service.client(),119 service.transaction_pool(),120 service.prometheus_registry().as_ref(),121 );122123 let client = service.client();124 let select_chain = service.select_chain()125 .ok_or(ServiceError::SelectChainRequired)?;126127 let can_author_with =128 sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone());129130 let aura = sc_consensus_aura::start_aura::<_, _, _, _, _, AuraPair, _, _, _>(131 sc_consensus_aura::slot_duration(&*client)?,132 client,133 select_chain,134 block_import,135 proposer,136 service.network(),137 inherent_data_providers.clone(),138 force_authoring,139 service.keystore(),140 can_author_with,141 )?;142143 // the AURA authoring task is considered essential, i.e. if it144 // fails we take down the service with it.145 service.spawn_essential_task_handle().spawn_blocking("aura", aura);146 }147148 // if the node isn't actively participating in consensus then it doesn't149 // need a keystore, regardless of which protocol we use below.150 let keystore = if role.is_authority() {151 Some(service.keystore() as sp_core::traits::BareCryptoStorePtr)152 } else {153 None154 };155156 let grandpa_config = sc_finality_grandpa::Config {157 // FIXME #1578 make this available through chainspec158 gossip_duration: Duration::from_millis(333),159 justification_period: 512,160 name: Some(name),161 observer_enabled: false,162 keystore,163 is_authority: role.is_network_authority(),164 };165166 let enable_grandpa = !disable_grandpa;167 if enable_grandpa {168 // start the full GRANDPA voter169 // NOTE: non-authorities could run the GRANDPA observer protocol, but at170 // this point the full voter should provide better guarantees of block171 // and vote data availability than the observer. The observer has not172 // been tested extensively yet and having most nodes in a network run it173 // could lead to finality stalls.174 let grandpa_config = sc_finality_grandpa::GrandpaParams {175 config: grandpa_config,176 link: grandpa_link,177 network: service.network(),178 inherent_data_providers: inherent_data_providers.clone(),179 telemetry_on_connect: Some(service.telemetry_on_connect_stream()),180 voting_rule: sc_finality_grandpa::VotingRulesBuilder::default().build(),181 prometheus_registry: service.prometheus_registry(),182 shared_voter_state: SharedVoterState::empty(),183 };184185 // the GRANDPA voter task is considered infallible, i.e.186 // if it fails we take down the service with it.187 service.spawn_essential_task_handle().spawn_blocking(188 "grandpa-voter",189 sc_finality_grandpa::run_grandpa_voter(grandpa_config)?190 );191 } else {192 sc_finality_grandpa::setup_disabled_grandpa(193 service.client(),194 &inherent_data_providers,195 service.network(),196 )?;197 }198199 Ok(service)200}201202/// Builds a new service for a light client.203pub fn new_light(config: Configuration) -> Result<impl AbstractService, ServiceError> {204 let inherent_data_providers = InherentDataProviders::new();205206 ServiceBuilder::new_light::<Block, RuntimeApi, Executor>(config)?207 .with_select_chain(|_config, backend| {208 Ok(LongestChain::new(backend.clone()))209 })?210 .with_transaction_pool(|builder| {211 let fetcher = builder.fetcher()212 .ok_or_else(|| "Trying to start light transaction pool without active fetcher")?;213214 let pool_api = sc_transaction_pool::LightChainApi::new(215 builder.client().clone(),216 fetcher.clone(),217 );218 let pool = sc_transaction_pool::BasicPool::with_revalidation_type(219 builder.config().transaction_pool.clone(),220 Arc::new(pool_api),221 builder.prometheus_registry(),222 sc_transaction_pool::RevalidationType::Light,223 );224 Ok(pool)225 })?226 .with_import_queue_and_fprb(|227 _config,228 client,229 backend,230 fetcher,231 _select_chain,232 _tx_pool,233 spawn_task_handle,234 prometheus_registry,235 | {236 let fetch_checker = fetcher237 .map(|fetcher| fetcher.checker().clone())238 .ok_or_else(|| "Trying to start light import queue without active fetch checker")?;239 let grandpa_block_import = sc_finality_grandpa::light_block_import(240 client.clone(),241 backend,242 &(client.clone() as Arc<_>),243 Arc::new(fetch_checker),244 )?;245 let finality_proof_import = grandpa_block_import.clone();246 let finality_proof_request_builder =247 finality_proof_import.create_finality_proof_request_builder();248249 let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _>(250 sc_consensus_aura::slot_duration(&*client)?,251 grandpa_block_import,252 None,253 Some(Box::new(finality_proof_import)),254 client,255 inherent_data_providers.clone(),256 spawn_task_handle,257 prometheus_registry,258 )?;259260 Ok((import_queue, finality_proof_request_builder))261 })?262 .with_finality_proof_provider(|client, backend| {263 // GenesisAuthoritySetProvider is implemented for StorageAndProofProvider264 let provider = client as Arc<dyn StorageAndProofProvider<_, _>>;265 Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, provider)) as _)266 })?267 .build_light()268}pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -58,10 +58,7 @@
/// Next available collection ID
pub NextCollectionID get(fn next_collection_id): u64;
-
pub Collection get(fn collection): map hasher(identity) u64 => CollectionType<T::AccountId>;
- //pub Collection get(collection): map hasher(identity) u64 => CollectionType<T::AccountId>;
-
pub AdminList get(fn admin_list_collection): map hasher(identity) u64 => Vec<T::AccountId>;
/// Balance owner per collection map
@@ -69,10 +66,10 @@
pub ApprovedList get(fn approved): map hasher(blake2_128_concat) (u64, u64) => Vec<T::AccountId>;
pub ItemList get(fn item_id): map hasher(blake2_128_concat) (u64, u64) => NftItemType<T::AccountId>;
- // pub ItemList get(item_id): map hasher(blake2_128_concat) (u64, u64) => NftItemType<T::AccountId>;
+ pub ItemListIndex get(fn item_index): map hasher(blake2_128_concat) u64 => u64;
+
+ pub AddressTokens get(fn address_tokens): map hasher(blake2_128_concat) (u64, T::AccountId) => Vec<u64>;
- pub ItemListIndex get(fn item_index): map hasher(blake2_128_concat) u64 => u64;
- // pub ItemListIndex get(item_index): map hasher(blake2_128_concat) u64 => u64;
}
}
@@ -247,7 +244,11 @@
data: properties,
};
+
let current_index = <ItemListIndex>::get(collection_id);
+
+ Self::add_token_index(collection_id, current_index, new_item.owner.clone())?;
+
<ItemListIndex>::insert(collection_id, current_index);
<ItemList<T>>::insert((collection_id, current_index), new_item);
@@ -279,6 +280,8 @@
}
<ItemList<T>>::remove((collection_id, item_id));
+ Self::remove_token_index(collection_id, item_id, item.owner.clone())?;
+
// update balance
let new_balance = <Balance<T>>::get((collection_id, item.owner.clone())) - 1;
<Balance<T>>::insert((collection_id, item.owner.clone()), new_balance);
@@ -319,9 +322,13 @@
<Balance<T>>::insert((collection_id, new_owner.clone()), balance_new_owner);
// change owner
- item.owner = new_owner;
+ let old_owner = item.owner.clone();
+ item.owner = new_owner.clone();
<ItemList<T>>::insert((collection_id, item_id), item);
+ // update index collection
+ Self::move_token_index(collection_id, item_id, old_owner, new_owner.clone())?;
+
// reset approved list
let itm: Vec<T::AccountId> = Vec::new();
<ApprovedList<T>>::insert((collection_id, item_id), itm);
@@ -401,3 +408,55 @@
}
}
}
+
+
+impl<T: Trait> Module<T> {
+ fn add_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {
+
+ let list_exists = <AddressTokens<T>>::contains_key((collection_id, owner.clone()));
+ if list_exists {
+
+ let mut list = <AddressTokens<T>>::get((collection_id, owner.clone()));
+ let item_contains = list.contains(&item_index.clone());
+
+ if !item_contains {
+ list.push(item_index.clone());
+ }
+
+ <AddressTokens<T>>::insert((collection_id, owner.clone()), list);
+
+ } else {
+
+ let mut itm = Vec::new();
+ itm.push(item_index.clone());
+ <AddressTokens<T>>::insert((collection_id, owner), itm);
+ }
+
+ Ok(())
+ }
+
+ fn remove_token_index(collection_id: u64, item_index: u64, owner: T::AccountId) -> DispatchResult {
+
+ let list_exists = <AddressTokens<T>>::contains_key((collection_id, owner.clone()));
+ if list_exists {
+
+ let mut list = <AddressTokens<T>>::get((collection_id, owner.clone()));
+ let item_contains = list.contains(&item_index.clone());
+
+ if item_contains {
+ list.retain(|&item| item != item_index);
+ <AddressTokens<T>>::insert((collection_id, owner), list);
+ }
+ }
+
+ Ok(())
+ }
+
+ fn move_token_index(collection_id: u64, item_index: u64, old_owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {
+
+ Self::remove_token_index(collection_id, item_index, old_owner)?;
+ Self::add_token_index(collection_id, item_index, new_owner)?;
+
+ Ok(())
+ }
+}
\ No newline at end of file
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)
+ }
+ }
+
}