use super::{code::WasmModule, Config};
use crate::wasm::{
AllowDeprecatedInterface, AllowUnstableInterface, Determinism, Environment, LoadedModule,
LoadingMode, WasmBlob,
};
use sp_core::Get;
use wasmi::{errors::LinkerError, CompilationMode, Func, Linker, StackLimits, Store};
pub struct Sandbox {
entry_point: Func,
store: Store<()>,
}
impl Sandbox {
pub fn invoke(&mut self) {
self.entry_point.call(&mut self.store, &[], &mut []).unwrap();
}
}
impl<T: Config> From<&WasmModule<T>> for Sandbox {
fn from(module: &WasmModule<T>) -> Self {
let contract = LoadedModule::new::<T>(
&module.code,
Determinism::Relaxed,
Some(StackLimits::default()),
LoadingMode::Checked,
CompilationMode::Eager,
)
.expect("Failed to load Wasm module");
let (mut store, _memory, instance) = WasmBlob::<T>::instantiate::<EmptyEnv, _>(
contract,
(),
&<T>::Schedule::get(),
AllowDeprecatedInterface::No,
)
.expect("Failed to create benchmarking Sandbox instance");
store
.set_fuel(u64::MAX)
.expect("We've set up engine to fuel consuming mode; qed");
let entry_point = instance
.start(&mut store)
.unwrap()
.get_export(&store, "call")
.unwrap()
.into_func()
.unwrap();
Self { entry_point, store }
}
}
struct EmptyEnv;
impl Environment<()> for EmptyEnv {
fn define(
_: &mut Store<()>,
_: &mut Linker<()>,
_: AllowUnstableInterface,
_: AllowDeprecatedInterface,
) -> Result<(), LinkerError> {
Ok(())
}
}