contracts: Convert to framev2 macros (#8157)

* contracts: Convert to framev2

* Reduce the API surface of the crate

* Remove unused import

* Merge import block

* Use pallet::metadata to reduce metadata diff

* Remove the explicit "Null" from AccountCounter
This commit is contained in:
Alexander Theißen
2021-02-22 16:18:24 +01:00
committed by GitHub
parent 4f4a0c5b38
commit b2f393945a
15 changed files with 673 additions and 668 deletions
@@ -17,7 +17,6 @@
use codec::{Encode, Decode, Joiner};
use frame_support::{
StorageMap,
traits::Currency,
weights::{GetDispatchInfo, DispatchInfo, DispatchClass},
};
+1 -1
View File
@@ -71,7 +71,7 @@ pub use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment, Currency
use pallet_session::{historical as pallet_session_historical};
use sp_inherents::{InherentData, CheckInherentsResult};
use static_assertions::const_assert;
use pallet_contracts::WeightInfo;
use pallet_contracts::weights::WeightInfo;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
@@ -42,6 +42,7 @@ use parity_wasm::elements::{Instruction, ValueType, BlockType};
use sp_runtime::traits::{Hash, Bounded, Zero};
use sp_std::{default::Default, convert::{TryInto}, vec::Vec, vec};
use pallet_contracts_primitives::RentProjection;
use frame_support::weights::Weight;
/// How many batches we do per API benchmark.
const API_BENCHMARK_BATCHES: u32 = 20;
@@ -18,7 +18,7 @@
//! A mechanism for runtime authors to augment the functionality of contracts.
//!
//! The runtime is able to call into any contract and retrieve the result using
//! [`bare_call`](crate::Module::bare_call). This already allows customization of runtime
//! [`bare_call`](crate::Pallet::bare_call). This already allows customization of runtime
//! behaviour by user generated code (contracts). However, often it is more straightforward
//! to allow the reverse behaviour: The contract calls into the runtime. We call the latter
//! one a "chain extension" because it allows the chain to extend the set of functions that are
@@ -37,7 +37,7 @@
//! [`charge_weight`](Environment::charge_weight) function must be called **before**
//! carrying out any action that causes the consumption of the chargeable weight.
//! It cannot be overstated how delicate of a process the creation of a chain extension
//! is. Check whether using [`bare_call`](crate::Module::bare_call) suffices for the
//! is. Check whether using [`bare_call`](crate::Pallet::bare_call) suffices for the
//! use case at hand.
//!
//! # Benchmarking
@@ -328,7 +328,7 @@ where
///
/// If the contract supplied buffer is smaller than the passed `buffer` an `Err` is returned.
/// If `allow_skip` is set to true the contract is allowed to skip the copying of the buffer
/// by supplying the guard value of [`u32::max_value()`] as `out_ptr`. The
/// by supplying the guard value of `u32::max_value()` as `out_ptr`. The
/// `weight_per_byte` is only charged when the write actually happens and is not skipped or
/// failed due to a too small output buffer.
pub fn write(
+29 -12
View File
@@ -16,7 +16,7 @@
// limitations under the License.
use crate::{
CodeHash, Event, RawEvent, Config, Module as Contracts,
CodeHash, Event, Config, Module as Contracts,
TrieId, BalanceOf, ContractInfo, gas::GasMeter, rent::Rent, storage::{self, Storage},
Error, ContractInfoOf, Schedule,
};
@@ -30,7 +30,7 @@ use frame_support::{
dispatch::{DispatchResult, DispatchError},
traits::{ExistenceRequirement, Currency, Time, Randomness, Get},
weights::Weight,
ensure, StorageMap,
ensure,
};
use pallet_contracts_primitives::{ErrorOrigin, ExecError, ExecReturnValue, ExecResult, ReturnFlags};
@@ -57,7 +57,11 @@ pub enum TransactorKind {
///
/// This interface is specialized to an account of the executing code, so all
/// operations are implicitly performed on that account.
pub trait Ext {
///
/// # Note
///
/// This trait is sealed and cannot be implemented by downstream crates.
pub trait Ext: sealing::Sealed {
type T: Config;
/// Returns the storage entry of the executing account by the given `key`.
@@ -446,7 +450,7 @@ where
.ok_or(Error::<T>::NewContractNotFunded)?;
// Deposit an instantiation event.
deposit_event::<T>(vec![], RawEvent::Instantiated(caller.clone(), dest.clone()));
deposit_event::<T>(vec![], Event::Instantiated(caller.clone(), dest.clone()));
Ok(output)
});
@@ -664,7 +668,7 @@ where
if let Some(ContractInfo::Alive(info)) = ContractInfoOf::<T>::take(&self_id) {
Storage::<T>::queue_trie_for_deletion(&info).map_err(|e| (e, 0))?;
let code_len = E::remove_user(info.code_hash);
Contracts::<T>::deposit_event(RawEvent::Terminated(self_id, beneficiary.clone()));
Contracts::<T>::deposit_event(Event::Terminated(self_id, beneficiary.clone()));
Ok(code_len)
} else {
panic!(
@@ -708,7 +712,7 @@ where
if let Ok(_) = result {
deposit_event::<Self::T>(
vec![],
RawEvent::Restored(
Event::Restored(
self.ctx.self_account.clone(),
dest,
code_hash,
@@ -754,7 +758,7 @@ where
fn deposit_event(&mut self, topics: Vec<T::Hash>, data: Vec<u8>) {
deposit_event::<Self::T>(
topics,
RawEvent::ContractEmitted(self.ctx.self_account.clone(), data)
Event::ContractEmitted(self.ctx.self_account.clone(), data)
);
}
@@ -799,6 +803,20 @@ fn deposit_event<T: Config>(
)
}
mod sealing {
use super::*;
pub trait Sealed {}
impl<'a, 'b: 'a, T: Config, E> Sealed for CallContext<'a, 'b, T, E> {}
#[cfg(test)]
impl Sealed for crate::wasm::MockExt {}
#[cfg(test)]
impl Sealed for &mut crate::wasm::MockExt {}
}
/// These tests exercise the executive layer.
///
/// In these tests the VM/loader are mocked. Instead of dealing with wasm bytecode they use simple closures.
@@ -809,13 +827,12 @@ mod tests {
use super::*;
use crate::{
gas::GasMeter, tests::{ExtBuilder, Test, Event as MetaEvent},
gas::Gas,
storage::Storage,
tests::{
ALICE, BOB, CHARLIE,
test_utils::{place_contract, set_balance, get_balance},
},
Error,
Error, Weight,
};
use sp_runtime::DispatchError;
use assert_matches::assert_matches;
@@ -823,7 +840,7 @@ mod tests {
type MockContext<'a> = ExecutionContext<'a, Test, MockExecutable>;
const GAS_LIMIT: Gas = 10_000_000_000;
const GAS_LIMIT: Weight = 10_000_000_000;
thread_local! {
static LOADER: RefCell<MockLoader> = RefCell::new(MockLoader::default());
@@ -1334,7 +1351,7 @@ mod tests {
// there are instantiation event.
assert_eq!(Storage::<Test>::code_hash(&instantiated_contract_address).unwrap(), dummy_ch);
assert_eq!(&events(), &[
RawEvent::Instantiated(ALICE, instantiated_contract_address)
Event::Instantiated(ALICE, instantiated_contract_address)
]);
});
}
@@ -1410,7 +1427,7 @@ mod tests {
// there are instantiation event.
assert_eq!(Storage::<Test>::code_hash(&instantiated_contract_address).unwrap(), dummy_ch);
assert_eq!(&events(), &[
RawEvent::Instantiated(BOB, instantiated_contract_address)
Event::Instantiated(BOB, instantiated_contract_address)
]);
});
}
+46 -50
View File
@@ -30,14 +30,11 @@ use sp_core::crypto::UncheckedFrom;
#[cfg(test)]
use std::{any::Any, fmt::Debug};
// Gas is essentially the same as weight. It is a 1 to 1 correspondence.
pub type Gas = Weight;
#[derive(Debug, PartialEq, Eq)]
pub struct ChargedAmount(Gas);
pub struct ChargedAmount(Weight);
impl ChargedAmount {
pub fn amount(&self) -> Gas {
pub fn amount(&self) -> Weight {
self.0
}
}
@@ -72,7 +69,7 @@ pub trait Token<T: Config>: Copy + Clone + TestAuxiliaries {
/// That said, implementors of this function still can run into overflows
/// while calculating the amount. In this case it is ok to use saturating operations
/// since on overflow they will return `max_value` which should consume all gas.
fn calculate_amount(&self, metadata: &Self::Metadata) -> Gas;
fn calculate_amount(&self, metadata: &Self::Metadata) -> Weight;
}
/// A wrapper around a type-erased trait object of what used to be a `Token`.
@@ -83,9 +80,9 @@ pub struct ErasedToken {
}
pub struct GasMeter<T: Config> {
gas_limit: Gas,
gas_limit: Weight,
/// Amount of gas left from initial gas limit. Can reach zero.
gas_left: Gas,
gas_left: Weight,
_phantom: PhantomData<T>,
#[cfg(test)]
tokens: Vec<ErasedToken>,
@@ -95,7 +92,7 @@ impl<T: Config> GasMeter<T>
where
T::AccountId: UncheckedFrom<<T as frame_system::Config>::Hash> + AsRef<[u8]>
{
pub fn new(gas_limit: Gas) -> Self {
pub fn new(gas_limit: Weight) -> Self {
GasMeter {
gas_limit,
gas_left: gas_limit,
@@ -177,7 +174,7 @@ where
/// All unused gas in the nested gas meter is returned to this gas meter.
pub fn with_nested<R, F: FnOnce(Option<&mut GasMeter<T>>) -> R>(
&mut self,
amount: Gas,
amount: Weight,
f: F,
) -> R {
// NOTE that it is ok to allocate all available gas since it still ensured
@@ -197,12 +194,12 @@ where
}
/// Returns how much gas was used.
pub fn gas_spent(&self) -> Gas {
pub fn gas_spent(&self) -> Weight {
self.gas_limit - self.gas_left
}
/// Returns how much gas left from the initial budget.
pub fn gas_left(&self) -> Gas {
pub fn gas_left(&self) -> Weight {
self.gas_left
}
@@ -230,49 +227,48 @@ where
}
}
/// A simple utility macro that helps to match against a
/// list of tokens.
#[macro_export]
macro_rules! match_tokens {
($tokens_iter:ident,) => {
};
($tokens_iter:ident, $x:expr, $($rest:tt)*) => {
{
let next = ($tokens_iter).next().unwrap();
let pattern = $x;
// Note that we don't specify the type name directly in this macro,
// we only have some expression $x of some type. At the same time, we
// have an iterator of Box<dyn Any> and to downcast we need to specify
// the type which we want downcast to.
//
// So what we do is we assign `_pattern_typed_next_ref` to a variable which has
// the required type.
//
// Then we make `_pattern_typed_next_ref = token.downcast_ref()`. This makes
// rustc infer the type `T` (in `downcast_ref<T: Any>`) to be the same as in $x.
let mut _pattern_typed_next_ref = &pattern;
_pattern_typed_next_ref = match next.token.downcast_ref() {
Some(p) => {
assert_eq!(p, &pattern);
p
}
None => {
panic!("expected type {} got {}", stringify!($x), next.description);
}
};
}
match_tokens!($tokens_iter, $($rest)*);
};
}
#[cfg(test)]
mod tests {
use super::{GasMeter, Token};
use crate::tests::Test;
/// A simple utility macro that helps to match against a
/// list of tokens.
macro_rules! match_tokens {
($tokens_iter:ident,) => {
};
($tokens_iter:ident, $x:expr, $($rest:tt)*) => {
{
let next = ($tokens_iter).next().unwrap();
let pattern = $x;
// Note that we don't specify the type name directly in this macro,
// we only have some expression $x of some type. At the same time, we
// have an iterator of Box<dyn Any> and to downcast we need to specify
// the type which we want downcast to.
//
// So what we do is we assign `_pattern_typed_next_ref` to a variable which has
// the required type.
//
// Then we make `_pattern_typed_next_ref = token.downcast_ref()`. This makes
// rustc infer the type `T` (in `downcast_ref<T: Any>`) to be the same as in $x.
let mut _pattern_typed_next_ref = &pattern;
_pattern_typed_next_ref = match next.token.downcast_ref() {
Some(p) => {
assert_eq!(p, &pattern);
p
}
None => {
panic!("expected type {} got {}", stringify!($x), next.description);
}
};
}
match_tokens!($tokens_iter, $($rest)*);
};
}
/// A trivial token that charges the specified number of gas units.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
struct SimpleToken(u64);
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -18,7 +18,7 @@
//! A module responsible for computing the right amount of weight and charging it.
use crate::{
AliveContractInfo, BalanceOf, ContractInfo, ContractInfoOf, Module, RawEvent,
AliveContractInfo, BalanceOf, ContractInfo, ContractInfoOf, Module, Event,
TombstoneContractInfo, Config, CodeHash, Error,
storage::Storage, wasm::PrefabWasmModule, exec::Executable,
};
@@ -26,7 +26,7 @@ use sp_std::prelude::*;
use sp_io::hashing::blake2_256;
use sp_core::crypto::UncheckedFrom;
use frame_support::{
debug, StorageMap,
debug,
storage::child,
traits::{Currency, ExistenceRequirement, Get, OnUnbalanced, WithdrawReasons},
};
@@ -268,7 +268,7 @@ where
let tombstone_info = ContractInfo::Tombstone(tombstone);
<ContractInfoOf<T>>::insert(account, &tombstone_info);
code.drop_from_storage();
<Module<T>>::deposit_event(RawEvent::Evicted(account.clone()));
<Module<T>>::deposit_event(Event::Evicted(account.clone()));
Ok(None)
}
(Verdict::Evict { amount: _ }, None) => {
+8 -9
View File
@@ -31,9 +31,8 @@ use sp_runtime::traits::{Bounded, Saturating, Zero};
use sp_core::crypto::UncheckedFrom;
use frame_support::{
dispatch::DispatchResult,
StorageMap,
debug,
storage::{child::{self, KillOutcome}, StorageValue},
storage::child::{self, KillOutcome},
traits::Get,
weights::Weight,
};
@@ -196,10 +195,10 @@ where
/// You must make sure that the contract is also removed or converted into a tombstone
/// when queuing the trie for deletion.
pub fn queue_trie_for_deletion(contract: &AliveContractInfo<T>) -> DispatchResult {
if DeletionQueue::decode_len().unwrap_or(0) >= T::DeletionQueueDepth::get() as usize {
if <DeletionQueue<T>>::decode_len().unwrap_or(0) >= T::DeletionQueueDepth::get() as usize {
Err(Error::<T>::DeletionQueueFull.into())
} else {
DeletionQueue::append(DeletedContract {
<DeletionQueue<T>>::append(DeletedContract {
pair_count: contract.pair_count,
trie_id: contract.trie_id.clone(),
});
@@ -234,7 +233,7 @@ where
/// It returns the amount of weight used for that task or `None` when no weight was used
/// apart from the base weight.
pub fn process_deletion_queue_batch(weight_limit: Weight) -> Weight {
let queue_len = DeletionQueue::decode_len().unwrap_or(0);
let queue_len = <DeletionQueue<T>>::decode_len().unwrap_or(0);
if queue_len == 0 {
return weight_limit;
}
@@ -251,7 +250,7 @@ where
return weight_limit;
}
let mut queue = DeletionQueue::get();
let mut queue = <DeletionQueue<T>>::get();
while !queue.is_empty() && remaining_key_budget > 0 {
// Cannot panic due to loop condition
@@ -283,7 +282,7 @@ where
.saturating_sub(remaining_key_budget.min(pair_count));
}
DeletionQueue::put(queue);
<DeletionQueue<T>>::put(queue);
weight_limit.saturating_sub(weight_per_key.saturating_mul(remaining_key_budget as Weight))
}
@@ -293,7 +292,7 @@ where
use sp_runtime::traits::Hash;
// Note that skipping a value due to error is not an issue here.
// We only need uniqueness, not sequence.
let new_seed = AccountCounter::mutate(|v| {
let new_seed = <AccountCounter<T>>::mutate(|v| {
*v = v.wrapping_add(1);
*v
});
@@ -322,6 +321,6 @@ where
trie_id: vec![],
})
.collect();
DeletionQueue::put(queue);
<DeletionQueue<T>>::put(queue);
}
}
+32 -19
View File
@@ -17,14 +17,15 @@
use crate::{
BalanceOf, ContractInfo, ContractInfoOf, Module,
RawAliveContractInfo, RawEvent, Config, Schedule, gas::Gas,
Error, RuntimeReturnCode, storage::Storage,
RawAliveContractInfo, Config, Schedule,
Error, storage::Storage,
chain_extension::{
Result as ExtensionResult, Environment, ChainExtension, Ext, SysConfig, RetVal,
UncheckedFrom, InitState, ReturnFlags,
},
exec::{AccountIdOf, Executable}, wasm::PrefabWasmModule,
weights::WeightInfo,
wasm::ReturnCode as RuntimeReturnCode,
};
use assert_matches::assert_matches;
use codec::Encode;
@@ -36,8 +37,8 @@ use sp_runtime::{
use sp_io::hashing::blake2_256;
use frame_support::{
assert_ok, assert_err, assert_err_ignore_postinfo,
parameter_types, StorageMap, StorageValue, assert_storage_noop,
traits::{Currency, ReservableCurrency, OnInitialize},
parameter_types, assert_storage_noop,
traits::{Currency, ReservableCurrency, OnInitialize, GenesisBuild},
weights::{Weight, PostDispatchInfo, DispatchClass, constants::WEIGHT_PER_SECOND},
dispatch::DispatchErrorWithPostInfo,
storage::child,
@@ -73,7 +74,7 @@ pub mod test_utils {
exec::{StorageKey, AccountIdOf},
Module as Contracts,
};
use frame_support::{StorageMap, traits::Currency};
use frame_support::traits::Currency;
pub fn set_storage(addr: &AccountIdOf<Test>, key: &StorageKey, value: Option<Vec<u8>>) {
let contract_info = <ContractInfoOf::<Test>>::get(&addr).unwrap().get_alive().unwrap();
@@ -292,7 +293,7 @@ pub const BOB: AccountId32 = AccountId32::new([2u8; 32]);
pub const CHARLIE: AccountId32 = AccountId32::new([3u8; 32]);
pub const DJANGO: AccountId32 = AccountId32::new([4u8; 32]);
const GAS_LIMIT: Gas = 10_000_000_000;
const GAS_LIMIT: Weight = 10_000_000_000;
pub struct ExtBuilder {
existential_deposit: u64,
@@ -501,19 +502,19 @@ fn instantiate_and_call_and_deposit_event() {
},
EventRecord {
phase: Phase::Initialization,
event: Event::pallet_contracts(RawEvent::CodeStored(code_hash.into())),
event: Event::pallet_contracts(crate::Event::CodeStored(code_hash.into())),
topics: vec![],
},
EventRecord {
phase: Phase::Initialization,
event: Event::pallet_contracts(
RawEvent::ContractEmitted(addr.clone(), vec![1, 2, 3, 4])
crate::Event::ContractEmitted(addr.clone(), vec![1, 2, 3, 4])
),
topics: vec![],
},
EventRecord {
phase: Phase::Initialization,
event: Event::pallet_contracts(RawEvent::Instantiated(ALICE, addr.clone())),
event: Event::pallet_contracts(crate::Event::Instantiated(ALICE, addr.clone())),
topics: vec![],
},
]);
@@ -1230,12 +1231,16 @@ fn restoration(
},
EventRecord {
phase: Phase::Initialization,
event: Event::pallet_contracts(RawEvent::CodeStored(set_rent_code_hash.into())),
event: Event::pallet_contracts(
crate::Event::CodeStored(set_rent_code_hash.into())
),
topics: vec![],
},
EventRecord {
phase: Phase::Initialization,
event: Event::pallet_contracts(RawEvent::Instantiated(ALICE, addr_bob.clone())),
event: Event::pallet_contracts(
crate::Event::Instantiated(ALICE, addr_bob.clone())
),
topics: vec![],
},
];
@@ -1275,7 +1280,9 @@ fn restoration(
},
EventRecord {
phase: Phase::Initialization,
event: Event::pallet_contracts(RawEvent::Instantiated(ALICE, addr_dummy.clone())),
event: Event::pallet_contracts(
crate::Event::Instantiated(ALICE, addr_dummy.clone())
),
topics: vec![],
},
].iter().cloned());
@@ -1401,7 +1408,7 @@ fn restoration(
assert_eq!(System::events(), vec![
EventRecord {
phase: Phase::Initialization,
event: Event::pallet_contracts(RawEvent::Evicted(addr_bob)),
event: Event::pallet_contracts(crate::Event::Evicted(addr_bob)),
topics: vec![],
},
EventRecord {
@@ -1433,12 +1440,16 @@ fn restoration(
},
EventRecord {
phase: Phase::Initialization,
event: Event::pallet_contracts(RawEvent::CodeStored(restoration_code_hash)),
event: Event::pallet_contracts(
crate::Event::CodeStored(restoration_code_hash)
),
topics: vec![],
},
EventRecord {
phase: Phase::Initialization,
event: Event::pallet_contracts(RawEvent::Instantiated(CHARLIE, addr_django.clone())),
event: Event::pallet_contracts(
crate::Event::Instantiated(CHARLIE, addr_django.clone())
),
topics: vec![],
},
@@ -1470,7 +1481,7 @@ fn restoration(
assert_eq!(System::events(), vec![
EventRecord {
phase: Phase::Initialization,
event: Event::pallet_contracts(RawEvent::CodeRemoved(restoration_code_hash)),
event: Event::pallet_contracts(crate::Event::CodeRemoved(restoration_code_hash)),
topics: vec![],
},
EventRecord {
@@ -1481,7 +1492,9 @@ fn restoration(
EventRecord {
phase: Phase::Initialization,
event: Event::pallet_contracts(
RawEvent::Restored(addr_django, addr_bob, bob_contract.code_hash, 50)
crate::Event::Restored(
addr_django, addr_bob, bob_contract.code_hash, 50
)
),
topics: vec![],
},
@@ -1720,13 +1733,13 @@ fn self_destruct_works() {
},
EventRecord {
phase: Phase::Initialization,
event: Event::pallet_contracts(RawEvent::CodeRemoved(code_hash)),
event: Event::pallet_contracts(crate::Event::CodeRemoved(code_hash)),
topics: vec![],
},
EventRecord {
phase: Phase::Initialization,
event: Event::pallet_contracts(
RawEvent::Terminated(addr.clone(), DJANGO)
crate::Event::Terminated(addr.clone(), DJANGO)
),
topics: vec![],
},
@@ -28,13 +28,13 @@
//! Thus, before executing a contract it should be reinstrument with new schedule.
use crate::{
CodeHash, CodeStorage, PristineCode, Schedule, Config, Error,
wasm::{prepare, PrefabWasmModule}, Module as Contracts, RawEvent,
gas::{Gas, GasMeter, Token},
CodeHash, CodeStorage, PristineCode, Schedule, Config, Error, Weight,
wasm::{prepare, PrefabWasmModule}, Module as Contracts, Event,
gas::{GasMeter, Token},
weights::WeightInfo,
};
use sp_core::crypto::UncheckedFrom;
use frame_support::{StorageMap, dispatch::DispatchError};
use frame_support::dispatch::DispatchError;
#[cfg(feature = "runtime-benchmarks")]
pub use self::private::reinstrument as reinstrument;
@@ -58,7 +58,7 @@ where
Some(module) => increment_64(&mut module.refcount),
None => {
*existing = Some(prefab_module);
Contracts::<T>::deposit_event(RawEvent::CodeStored(code_hash))
Contracts::<T>::deposit_event(Event::CodeStored(code_hash))
}
}
});
@@ -170,7 +170,7 @@ where
T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]>
{
<PristineCode<T>>::remove(code_hash);
Contracts::<T>::deposit_event(RawEvent::CodeRemoved(code_hash))
Contracts::<T>::deposit_event(Event::CodeRemoved(code_hash))
}
/// Increment the refcount panicking if it should ever overflow (which will not happen).
@@ -196,7 +196,7 @@ struct InstrumentToken(u32);
impl<T: Config> Token<T> for InstrumentToken {
type Metadata = ();
fn calculate_amount(&self, _metadata: &Self::Metadata) -> Gas {
fn calculate_amount(&self, _metadata: &Self::Metadata) -> Weight {
T::WeightInfo::instrument(self.0 / 1024)
}
}
@@ -20,13 +20,11 @@
//!
//! Most likely you should use `define_env` macro.
#[macro_export]
macro_rules! convert_args {
() => (vec![]);
( $( $t:ty ),* ) => ( vec![ $( { use $crate::wasm::env_def::ConvertibleToWasm; <$t>::VALUE_TYPE }, )* ] );
}
#[macro_export]
macro_rules! gen_signature {
( ( $( $params: ty ),* ) ) => (
{
@@ -43,7 +41,6 @@ macro_rules! gen_signature {
);
}
#[macro_export]
macro_rules! gen_signature_dispatch {
(
$needle_name:ident,
@@ -102,7 +99,6 @@ where
f
}
#[macro_export]
macro_rules! unmarshall_then_body_then_marshall {
( $args_iter:ident, $ctx:ident, ( $( $names:ident : $params:ty ),* ) -> $returns:ty => $body:tt ) => ({
let body = $crate::wasm::env_def::macros::constrain_closure::<
@@ -128,7 +124,6 @@ macro_rules! unmarshall_then_body_then_marshall {
})
}
#[macro_export]
macro_rules! define_func {
( < E: $seal_ty:tt > $name:ident ( $ctx: ident $(, $names:ident : $params:ty)*) $(-> $returns:ty)* => $body:tt ) => {
fn $name< E: $seal_ty >(
@@ -152,7 +147,6 @@ macro_rules! define_func {
};
}
#[macro_export]
macro_rules! register_func {
( $reg_cb:ident, < E: $seal_ty:tt > ; ) => {};
@@ -215,9 +209,9 @@ mod tests {
use sp_runtime::traits::Zero;
use sp_sandbox::{ReturnValue, Value};
use crate::{
Weight,
wasm::{Runtime, runtime::TrapReason, tests::MockExt},
exec::Ext,
gas::Gas,
};
struct TestRuntime {
@@ -282,7 +276,7 @@ mod tests {
#[test]
fn macro_define_func() {
define_func!( <E: Ext> seal_gas (_ctx, amount: u32) => {
let amount = Gas::from(amount);
let amount = Weight::from(amount);
if !amount.is_zero() {
Ok(())
} else {
@@ -334,7 +328,7 @@ mod tests {
define_env!(Env, <E: Ext>,
seal_gas( _ctx, amount: u32 ) => {
let amount = Gas::from(amount);
let amount = Weight::from(amount);
if !amount.is_zero() {
Ok(())
} else {
@@ -22,7 +22,7 @@ use sp_sandbox::Value;
use parity_wasm::elements::{FunctionType, ValueType};
#[macro_use]
pub(crate) mod macros;
pub mod macros;
pub trait ConvertibleToWasm: Sized {
const VALUE_TYPE: ValueType;
@@ -67,13 +67,13 @@ impl ConvertibleToWasm for u64 {
}
}
pub(crate) type HostFunc<E> =
pub type HostFunc<E> =
fn(
&mut Runtime<E>,
&[sp_sandbox::Value]
) -> Result<sp_sandbox::ReturnValue, sp_sandbox::HostError>;
pub(crate) trait FunctionImplProvider<E: Ext> {
pub trait FunctionImplProvider<E: Ext> {
fn impls<F: FnMut(&[u8], HostFunc<E>)>(f: &mut F);
}
+5 -3
View File
@@ -38,6 +38,8 @@ use pallet_contracts_primitives::ExecResult;
pub use self::runtime::{ReturnCode, Runtime, RuntimeToken};
#[cfg(feature = "runtime-benchmarks")]
pub use self::code_cache::reinstrument;
#[cfg(test)]
pub use tests::MockExt;
/// A prepared wasm module ready for execution.
///
@@ -237,7 +239,7 @@ mod tests {
use crate::{
CodeHash, BalanceOf, Error, Module as Contracts,
exec::{Ext, StorageKey, AccountIdOf, Executable},
gas::{Gas, GasMeter},
gas::GasMeter,
tests::{Test, Call, ALICE, BOB},
};
use std::collections::HashMap;
@@ -248,7 +250,7 @@ mod tests {
use assert_matches::assert_matches;
use pallet_contracts_primitives::{ExecReturnValue, ReturnFlags, ExecError, ErrorOrigin};
const GAS_LIMIT: Gas = 10_000_000_000;
const GAS_LIMIT: Weight = 10_000_000_000;
#[derive(Debug, PartialEq, Eq)]
struct DispatchEntry(Call);
@@ -1202,7 +1204,7 @@ mod tests {
&mut gas_meter,
).unwrap();
let gas_left = Gas::decode(&mut output.data.as_slice()).unwrap();
let gas_left = Weight::decode(&mut output.data.as_slice()).unwrap();
assert!(gas_left < GAS_LIMIT, "gas_left must be less than initial");
assert!(gas_left > gas_meter.gas_left(), "gas_left must be greater than final");
}
@@ -20,11 +20,11 @@
use crate::{
HostFnWeights, Config, CodeHash, BalanceOf, Error,
exec::{Ext, StorageKey, TopicOf},
gas::{Gas, GasMeter, Token, ChargedAmount},
gas::{GasMeter, Token, ChargedAmount},
wasm::env_def::ConvertibleToWasm,
};
use parity_wasm::elements::ValueType;
use frame_support::{dispatch::DispatchError, ensure, traits::Get};
use frame_support::{dispatch::DispatchError, ensure, traits::Get, weights::Weight};
use sp_std::prelude::*;
use codec::{Decode, DecodeAll, Encode};
use sp_runtime::traits::SaturatedConversion;
@@ -223,7 +223,7 @@ where
{
type Metadata = HostFnWeights<T>;
fn calculate_amount(&self, s: &Self::Metadata) -> Gas {
fn calculate_amount(&self, s: &Self::Metadata) -> Weight {
use self::RuntimeToken::*;
match *self {
MeteringBlock(amount) => s.gas.saturating_add(amount.into()),