Update srml-contract to Rust 2018. (#1510)

* Fix imports.

* Remove redundant binding

* Clean extern crates.

* Add comment

* Re-export macros from prelude

* Build fixes

* Update core/sr-std/src/lib.rs

Co-Authored-By: pepyakin <s.pepyakin@gmail.com>
This commit is contained in:
Sergei Pepyakin
2019-01-24 16:26:53 +01:00
committed by GitHub
parent 5be237030d
commit a5cafa68b1
13 changed files with 95 additions and 108 deletions
+5
View File
@@ -45,4 +45,9 @@ pub mod prelude {
pub use ::boxed::Box;
pub use ::cmp::{Eq, PartialEq};
pub use ::clone::Clone;
// Re-export `vec!` macro here, but not in `std` mode, since
// std's prelude already brings `vec!` into the scope.
#[cfg(not(feature = "std"))]
pub use ::vec;
}
+13 -12
View File
@@ -2,6 +2,7 @@
name = "srml-contract"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
[dependencies]
serde = { version = "1.0", default-features = false }
@@ -10,13 +11,13 @@ parity-codec = { version = "2.2", default-features = false }
parity-codec-derive = { version = "2.1", default-features = false }
parity-wasm = { version = "0.31", default-features = false }
substrate-primitives = { path = "../../core/primitives", default-features = false }
sr-primitives = { path = "../../core/sr-primitives", default-features = false }
sr-io = { path = "../../core/sr-io", default-features = false }
sr-std = { path = "../../core/sr-std", default-features = false }
sr-sandbox = { path = "../../core/sr-sandbox", default-features = false }
runtime-primitives = { package = "sr-primitives", path = "../../core/sr-primitives", default-features = false }
runtime-io = { package = "sr-io", path = "../../core/sr-io", default-features = false }
rstd = { package = "sr-std", path = "../../core/sr-std", default-features = false }
sandbox = { package = "sr-sandbox", path = "../../core/sr-sandbox", default-features = false }
srml-support = { path = "../support", default-features = false }
srml-system = { path = "../system", default-features = false }
srml-balances = { path = "../balances", default-features = false }
system = { package = "srml-system", path = "../system", default-features = false }
balances = { package = "srml-balances", path = "../balances", default-features = false }
[dev-dependencies]
wabt = "~0.7.4"
@@ -30,13 +31,13 @@ std = [
"parity-codec/std",
"parity-codec-derive/std",
"substrate-primitives/std",
"sr-primitives/std",
"sr-io/std",
"sr-std/std",
"srml-balances/std",
"sr-sandbox/std",
"runtime-primitives/std",
"runtime-io/std",
"rstd/std",
"balances/std",
"sandbox/std",
"srml-support/std",
"srml-system/std",
"system/std",
"parity-wasm/std",
"pwasm-utils/std",
]
+1 -1
View File
@@ -17,11 +17,11 @@
//! Auxilliaries to help with managing partial changes to accounts state.
use super::{CodeHash, CodeHashOf, StorageOf, Trait};
use {balances, system};
use rstd::cell::RefCell;
use rstd::collections::btree_map::{BTreeMap, Entry};
use rstd::prelude::*;
use runtime_support::{StorageMap, StorageDoubleMap};
use {balances, system};
pub struct ChangeEntry<T: Trait> {
balance: Option<T::Balance>,
+11 -8
View File
@@ -15,8 +15,8 @@
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
use super::{CodeHash, Config, ContractAddressFor, Event, RawEvent, Trait};
use account_db::{AccountDb, DirectAccountDb, OverlayAccountDb};
use gas::{GasMeter, Token, approx_gas_for_balance};
use crate::account_db::{AccountDb, DirectAccountDb, OverlayAccountDb};
use crate::gas::{GasMeter, Token, approx_gas_for_balance};
use balances::{self, EnsureAccountLiquid};
use rstd::prelude::*;
@@ -285,8 +285,10 @@ where
let mut output_data = Vec::new();
let (change_set, events, calls) = {
let mut overlay = OverlayAccountDb::new(&self.overlay);
let mut nested = self.nested(overlay, dest.clone());
let mut nested = self.nested(
OverlayAccountDb::new(&self.overlay),
dest.clone()
);
if value > T::Balance::zero() {
transfer(
@@ -608,15 +610,16 @@ mod tests {
ExecFeeToken, ExecutionContext, Ext, Loader, EmptyOutputBuf, TransferFeeKind, TransferFeeToken,
Vm, VmExecResult, InstantiateReceipt, RawEvent,
};
use account_db::AccountDb;
use gas::GasMeter;
use crate::account_db::AccountDb;
use crate::gas::GasMeter;
use crate::tests::{ExtBuilder, Test};
use crate::{CodeHash, Config};
use runtime_io::with_externalities;
use std::cell::RefCell;
use std::collections::HashMap;
use std::marker::PhantomData;
use std::rc::Rc;
use tests::{ExtBuilder, Test};
use {CodeHash, Config};
use assert_matches::assert_matches;
const ALICE: u64 = 1;
const BOB: u64 = 2;
+2 -2
View File
@@ -14,10 +14,10 @@
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
use crate::{GasSpent, Module, Trait};
use balances;
use runtime_primitives::traits::{As, CheckedMul, CheckedSub, Zero};
use runtime_support::StorageValue;
use {GasSpent, Module, Trait};
#[cfg(test)]
use std::{any::Any, fmt::Debug};
@@ -295,7 +295,7 @@ macro_rules! match_tokens {
#[cfg(test)]
mod tests {
use super::{GasMeter, Token};
use tests::Test;
use crate::tests::Test;
/// A trivial token that charges 1 unit of gas.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
+9 -36
View File
@@ -52,41 +52,14 @@
#![cfg_attr(not(feature = "std"), no_std)]
// We need these `extern crate` to be placed here otherwise there will be errors.
// TODO: https://github.com/paritytech/substrate/issues/1509
#[macro_use]
extern crate parity_codec_derive;
extern crate parity_wasm;
extern crate pwasm_utils;
extern crate parity_codec as codec;
extern crate sr_io as runtime_io;
extern crate sr_sandbox as sandbox;
#[cfg_attr(not(feature = "std"), macro_use)]
extern crate sr_std as rstd;
extern crate srml_balances as balances;
extern crate srml_system as system;
#[macro_use]
extern crate srml_support as runtime_support;
extern crate sr_primitives as runtime_primitives;
#[cfg(test)]
extern crate substrate_primitives;
#[cfg(test)]
#[macro_use]
extern crate assert_matches;
#[cfg(test)]
extern crate wabt;
#[cfg(test)]
#[macro_use]
extern crate hex_literal;
#[macro_use]
mod gas;
@@ -97,8 +70,8 @@ mod wasm;
#[cfg(test)]
mod tests;
use exec::ExecutionContext;
use account_db::AccountDb;
use crate::exec::ExecutionContext;
use crate::account_db::AccountDb;
use rstd::prelude::*;
use rstd::marker::PhantomData;
@@ -234,8 +207,8 @@ decl_module! {
let mut gas_meter = gas::buy_gas::<T>(&origin, gas_limit)?;
let cfg = Config::preload();
let vm = ::wasm::WasmVm::new(&cfg.schedule);
let loader = ::wasm::WasmLoader::new(&cfg.schedule);
let vm = crate::wasm::WasmVm::new(&cfg.schedule);
let loader = crate::wasm::WasmLoader::new(&cfg.schedule);
let mut ctx = ExecutionContext::top_level(origin.clone(), &cfg, &vm, &loader);
let result = ctx.call(dest, value, &mut gas_meter, &data, exec::EmptyOutputBuf::new());
@@ -288,8 +261,8 @@ decl_module! {
let mut gas_meter = gas::buy_gas::<T>(&origin, gas_limit)?;
let cfg = Config::preload();
let vm = ::wasm::WasmVm::new(&cfg.schedule);
let loader = ::wasm::WasmLoader::new(&cfg.schedule);
let vm = crate::wasm::WasmVm::new(&cfg.schedule);
let loader = crate::wasm::WasmLoader::new(&cfg.schedule);
let mut ctx = ExecutionContext::top_level(origin.clone(), &cfg, &vm, &loader);
let result = ctx.instantiate(endowment, &mut gas_meter, &code_hash, &data);
@@ -380,7 +353,7 @@ decl_storage! {
/// The storage items associated with an account/key.
///
/// TODO: keys should also be able to take AsRef<KeyType> to ensure Vec<u8>s can be passed as &[u8]
pub(crate) struct StorageOf<T>(::rstd::marker::PhantomData<T>);
pub(crate) struct StorageOf<T>(rstd::marker::PhantomData<T>);
impl<T: Trait> StorageDoubleMap for StorageOf<T> {
const PREFIX: &'static [u8] = b"con:sto:";
type Key1 = T::AccountId;
+8 -5
View File
@@ -23,13 +23,16 @@ use runtime_io::with_externalities;
use runtime_primitives::testing::{Digest, DigestItem, H256, Header};
use runtime_primitives::traits::{BlakeTwo256, IdentityLookup};
use runtime_primitives::BuildStorage;
use runtime_io;
use runtime_support::{StorageMap, StorageDoubleMap};
use substrate_primitives::{Blake2Hasher};
use system::{ensure_signed, Phase, EventRecord};
use wabt;
use {
balances, runtime_io, system, ComputeDispatchFee, ContractAddressFor, GenesisConfig, Module, RawEvent, StorageOf,
Trait
use system::{self, Phase, EventRecord};
use {wabt, balances};
use hex_literal::*;
use assert_matches::assert_matches;
use crate::{
ContractAddressFor, GenesisConfig, Module, RawEvent, StorageOf,
Trait, ComputeDispatchFee
};
mod contract {
@@ -25,12 +25,12 @@
//! this guarantees that every instrumented contract code in cache cannot have the version equal to the current one.
//! Thus, before executing a contract it should be reinstrument with new schedule.
use gas::{GasMeter, Token};
use crate::gas::{GasMeter, Token};
use crate::wasm::{prepare, runtime::Env, PrefabWasmModule};
use crate::{CodeHash, CodeStorage, PristineCode, Schedule, Trait};
use rstd::prelude::*;
use runtime_primitives::traits::{As, CheckedMul, Hash, Bounded};
use runtime_support::StorageMap;
use wasm::{prepare, runtime::Env, PrefabWasmModule};
use {CodeHash, CodeStorage, PristineCode, Schedule, Trait};
/// Gas metering token that used for charging storing code into the code storage.
///
@@ -29,13 +29,13 @@ macro_rules! convert_args {
macro_rules! gen_signature {
( ( $( $params: ty ),* ) ) => (
{
$crate::parity_wasm::elements::FunctionType::new(convert_args!($($params),*), None)
parity_wasm::elements::FunctionType::new(convert_args!($($params),*), None)
}
);
( ( $( $params: ty ),* ) -> $returns: ty ) => (
{
$crate::parity_wasm::elements::FunctionType::new(convert_args!($($params),*), Some({
parity_wasm::elements::FunctionType::new(convert_args!($($params),*), Some({
use $crate::wasm::env_def::ConvertibleToWasm; <$returns>::VALUE_TYPE
}))
}
@@ -96,7 +96,7 @@ macro_rules! unmarshall_then_body {
#[inline(always)]
pub fn constrain_closure<R, F>(f: F) -> F
where
F: FnOnce() -> Result<R, ::sandbox::HostError>,
F: FnOnce() -> Result<R, sandbox::HostError>,
{
f
}
@@ -110,14 +110,14 @@ macro_rules! unmarshall_then_body_then_marshall {
unmarshall_then_body!($body, $ctx, $args_iter, $( $names : $params ),*)
});
let r = body()?;
return Ok($crate::sandbox::ReturnValue::Value({ use $crate::wasm::env_def::ConvertibleToWasm; r.to_typed_value() }))
return Ok(sandbox::ReturnValue::Value({ use $crate::wasm::env_def::ConvertibleToWasm; r.to_typed_value() }))
});
( $args_iter:ident, $ctx:ident, ( $( $names:ident : $params:ty ),* ) => $body:tt ) => ({
let body = $crate::wasm::env_def::macros::constrain_closure::<(), _>(|| {
unmarshall_then_body!($body, $ctx, $args_iter, $( $names : $params ),*)
});
body()?;
return Ok($crate::sandbox::ReturnValue::Unit)
return Ok(sandbox::ReturnValue::Unit)
})
}
@@ -126,7 +126,7 @@ macro_rules! define_func {
( < E: $ext_ty:tt > $name:ident ( $ctx: ident $(, $names:ident : $params:ty)*) $(-> $returns:ty)* => $body:tt ) => {
fn $name< E: $ext_ty >(
$ctx: &mut $crate::wasm::Runtime<E>,
args: &[$crate::sandbox::TypedValue],
args: &[sandbox::TypedValue],
) -> Result<sandbox::ReturnValue, sandbox::HostError> {
#[allow(unused)]
let mut args = args.iter();
@@ -176,7 +176,7 @@ macro_rules! define_env {
pub struct $init_name;
impl $crate::wasm::env_def::ImportSatisfyCheck for $init_name {
fn can_satisfy(name: &[u8], func_type: &$crate::parity_wasm::elements::FunctionType) -> bool {
fn can_satisfy(name: &[u8], func_type: &parity_wasm::elements::FunctionType) -> bool {
gen_signature_dispatch!( name, func_type ; $( $name ( $ctx $(, $names : $params )* ) $( -> $returns )* , )* );
return false;
@@ -197,10 +197,10 @@ mod tests {
use parity_wasm::elements::ValueType;
use runtime_primitives::traits::{As, Zero};
use sandbox::{self, ReturnValue, TypedValue};
use wasm::tests::MockExt;
use wasm::Runtime;
use exec::Ext;
use Trait;
use crate::wasm::tests::MockExt;
use crate::wasm::Runtime;
use crate::exec::Ext;
use crate::Trait;
#[test]
fn macro_unmarshall_then_body_then_marshall_value_or_trap() {
@@ -304,7 +304,7 @@ mod tests {
#[test]
fn macro_define_env() {
use wasm::env_def::ImportSatisfyCheck;
use crate::wasm::env_def::ImportSatisfyCheck;
define_env!(Env, <E: Ext>,
ext_gas( _ctx, amount: u32 ) => {
@@ -15,9 +15,10 @@
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
use super::Runtime;
use exec::Ext;
use parity_wasm::elements::{FunctionType, ValueType};
use crate::exec::Ext;
use sandbox::{self, TypedValue};
use parity_wasm::elements::{FunctionType, ValueType};
#[macro_use]
pub(crate) mod macros;
@@ -26,7 +27,7 @@ pub trait ConvertibleToWasm: Sized {
const VALUE_TYPE: ValueType;
type NativeType;
fn to_typed_value(self) -> TypedValue;
fn from_typed_value(TypedValue) -> Option<Self>;
fn from_typed_value(_: TypedValue) -> Option<Self>;
}
impl ConvertibleToWasm for i32 {
type NativeType = i32;
+15 -15
View File
@@ -17,13 +17,14 @@
//! This module provides a means for executing contracts
//! represented in wasm.
use codec::Compact;
use exec::{Ext, EmptyOutputBuf, VmExecResult};
use gas::GasMeter;
use crate::{CodeHash, Schedule, Trait};
use crate::wasm::env_def::FunctionImplProvider;
use crate::exec::{Ext, EmptyOutputBuf, VmExecResult};
use crate::gas::GasMeter;
use rstd::prelude::*;
use sandbox;
use wasm::env_def::FunctionImplProvider;
use {CodeHash, Schedule, Trait};
#[macro_use]
mod env_def;
@@ -72,7 +73,7 @@ impl<'a, T: Trait> WasmLoader<'a, T> {
}
}
impl<'a, T: Trait> ::exec::Loader<T> for WasmLoader<'a, T> {
impl<'a, T: Trait> crate::exec::Loader<T> for WasmLoader<'a, T> {
type Executable = WasmExecutable;
fn load_init(&self, code_hash: &CodeHash<T>) -> Result<WasmExecutable, &'static str> {
@@ -102,7 +103,7 @@ impl<'a, T: Trait> WasmVm<'a, T> {
}
}
impl<'a, T: Trait> ::exec::Vm<T> for WasmVm<'a, T> {
impl<'a, T: Trait> crate::exec::Vm<T> for WasmVm<'a, T> {
type Executable = WasmExecutable;
fn execute<E: Ext<T = T>>(
@@ -173,13 +174,12 @@ mod tests {
use super::*;
use std::collections::HashMap;
use substrate_primitives::H256;
use exec::{CallReceipt, Ext, InstantiateReceipt, EmptyOutputBuf};
use balances;
use gas::GasMeter;
use tests::{Test, Call};
use crate::exec::{CallReceipt, Ext, InstantiateReceipt, EmptyOutputBuf};
use crate::gas::GasMeter;
use crate::tests::{Test, Call};
use wabt;
use wasm::prepare::prepare_contract;
use CodeHash;
use crate::wasm::prepare::prepare_contract;
use crate::CodeHash;
#[derive(Debug, PartialEq, Eq)]
struct DispatchEntry(Call);
@@ -276,10 +276,10 @@ mod tests {
ext: &mut E,
gas_meter: &mut GasMeter<E::T>,
) -> Result<(), &'static str> {
use exec::Vm;
use crate::exec::Vm;
let wasm = wabt::wat2wasm(wat).unwrap();
let schedule = ::Schedule::<u64>::default();
let schedule = crate::Schedule::<u64>::default();
let prefab_module =
prepare_contract::<Test, super::runtime::Env>(&wasm, &schedule).unwrap();
+7 -5
View File
@@ -18,14 +18,15 @@
//! wasm module before execution. It also extracts some essential information
//! from a module.
use crate::wasm::env_def::ImportSatisfyCheck;
use crate::wasm::PrefabWasmModule;
use crate::{Schedule, Trait};
use parity_wasm::elements::{self, Internal, External, MemoryType, Type};
use pwasm_utils;
use pwasm_utils::rules;
use rstd::prelude::*;
use runtime_primitives::traits::As;
use wasm::env_def::ImportSatisfyCheck;
use wasm::PrefabWasmModule;
use {Schedule, Trait};
struct ContractModule<'a, Gas: 'a> {
// An `Option` is used here for loaning (`take()`-ing) the module.
@@ -316,10 +317,11 @@ pub fn prepare_contract<T: Trait, C: ImportSatisfyCheck>(
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::Test;
use crate::exec::Ext;
use std::fmt;
use tests::Test;
use exec::Ext;
use wabt;
use assert_matches::assert_matches;
impl fmt::Debug for PrefabWasmModule {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+5 -6
View File
@@ -16,16 +16,15 @@
//! Environment definition of the wasm smart-contract runtime.
use super::{Schedule};
use exec::{Ext, BalanceOf, VmExecResult, OutputBuf, EmptyOutputBuf, CallReceipt, InstantiateReceipt};
use crate::{Schedule, Trait, CodeHash, ComputeDispatchFee};
use crate::exec::{Ext, BalanceOf, VmExecResult, OutputBuf, EmptyOutputBuf, CallReceipt, InstantiateReceipt};
use crate::gas::{GasMeter, Token, GasMeterResult, approx_gas_for_balance};
use sandbox;
use system;
use rstd::prelude::*;
use rstd::mem;
use codec::{Decode, Encode};
use gas::{GasMeter, Token, GasMeterResult, approx_gas_for_balance};
use runtime_primitives::traits::{As, CheckedMul, Bounded};
use sandbox;
use system;
use {Trait, CodeHash, ComputeDispatchFee};
/// Enumerates all possible *special* trap conditions.
///