1234567891011121314151617#![cfg_attr(not(feature = "std"), no_std)]1819extern crate self as pallet_evm_coder_substrate;2021#[cfg(not(feature = "std"))]22extern crate alloc;23#[cfg(not(feature = "std"))]24use alloc::format;25use execution::PreDispatch;26use frame_support::dispatch::Weight;2728use core::marker::PhantomData;29use sp_std::{cell::RefCell, vec::Vec};3031use codec::Decode;32use frame_support::pallet_prelude::DispatchError;33use frame_support::traits::PalletInfo;34use frame_support::{ensure, sp_runtime::ModuleError};35use up_data_structs::budget;36use pallet_evm::{37 ExitError, ExitRevert, ExitSucceed, GasWeightMapping, PrecompileFailure, PrecompileOutput,38 PrecompileResult, PrecompileHandle,39};40use sp_core::{Get, H160};414243pub mod execution;4445#[doc(hidden)]46pub use spez::spez;4748use evm_coder::{49 types::{Msg, Value},50 AbiEncode,51};5253pub use pallet::*;54pub use evm_coder::{ResultWithPostInfoOf, Contract, abi, solidity_interface, ToLog, types};5556#[frame_support::pallet]57pub mod pallet {58 use super::*;5960 pub use frame_support::dispatch::DispatchResult;6162 63 64 65 66 67 #[pallet::error]68 pub enum Error<T> {69 OutOfGas,70 OutOfFund,71 }7273 #[pallet::config]74 pub trait Config: frame_system::Config + pallet_evm::Config {}7576 #[pallet::pallet]77 pub struct Pallet<T>(_);78}798081pub const G_SLOAD_WORD: u64 = 800;82pub const G_SSTORE_WORD: u64 = 20000;8384pub struct GasCallsBudget<'r, T: Config> {85 recorder: &'r SubstrateRecorder<T>,86 gas_per_call: u64,87}88impl<T: Config> budget::Budget for GasCallsBudget<'_, T> {89 fn consume_custom(&self, calls: u32) -> bool {90 let (gas, overflown) = (calls as u64).overflowing_add(self.gas_per_call);91 if overflown {92 return false;93 }94 self.recorder.consume_gas(gas).is_ok()95 }96}9798#[derive(Default)]99pub struct SubstrateRecorder<T: Config> {100 initial_gas: u64,101 gas_limit: RefCell<u64>,102 _phantom: PhantomData<*const T>,103}104105impl<T: Config> SubstrateRecorder<T> {106 pub fn new(gas_limit: u64) -> Self {107 Self {108 initial_gas: gas_limit,109 gas_limit: RefCell::new(gas_limit),110 _phantom: PhantomData,111 }112 }113114 pub fn gas_left(&self) -> u64 {115 *self.gas_limit.borrow()116 }117 pub fn gas_calls_budget(&self, gas_per_call: u64) -> GasCallsBudget<T> {118 GasCallsBudget {119 recorder: self,120 gas_per_call,121 }122 }123 pub fn weight_calls_budget(&self, weight_per_call: Weight) -> GasCallsBudget<T> {124 GasCallsBudget {125 recorder: self,126 gas_per_call: T::GasWeightMapping::weight_to_gas(weight_per_call),127 }128 }129 pub fn consume_sload_sub(&self) -> DispatchResult {130 self.consume_gas_sub(G_SLOAD_WORD)131 }132 pub fn consume_sstores_sub(&self, amount: usize) -> DispatchResult {133 self.consume_gas_sub(G_SSTORE_WORD.saturating_mul(amount as u64))134 }135 pub fn consume_sstore_sub(&self) -> DispatchResult {136 self.consume_gas_sub(G_SSTORE_WORD)137 }138 pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {139 ensure!(gas != u64::MAX, Error::<T>::OutOfGas);140 let mut gas_limit = self.gas_limit.borrow_mut();141 ensure!(gas <= *gas_limit, Error::<T>::OutOfGas);142 *gas_limit -= gas;143 Ok(())144 }145146 pub fn consume_sload(&self) -> execution::Result<()> {147 self.consume_gas(G_SLOAD_WORD)148 }149 pub fn consume_sstore(&self) -> execution::Result<()> {150 self.consume_gas(G_SSTORE_WORD)151 }152 pub fn consume_gas(&self, gas: u64) -> execution::Result<()> {153 if gas == u64::MAX {154 return Err(execution::Error::Error(ExitError::OutOfGas));155 }156 let mut gas_limit = self.gas_limit.borrow_mut();157 if gas > *gas_limit {158 return Err(execution::Error::Error(ExitError::OutOfGas));159 }160 *gas_limit -= gas;161 Ok(())162 }163 pub fn return_gas(&self, gas: u64) {164 let mut gas_limit = self.gas_limit.borrow_mut();165 *gas_limit += gas;166 }167168 pub fn evm_to_precompile_output(169 self,170 handle: &mut impl PrecompileHandle,171 result: execution::Result<Option<Vec<u8>>>,172 ) -> Option<PrecompileResult> {173 use execution::Error;174 175 let _ = handle.record_cost(self.initial_gas - self.gas_left());176 Some(match result {177 Ok(Some(v)) => Ok(PrecompileOutput {178 exit_status: ExitSucceed::Returned,179 output: v,180 }),181 Ok(None) => return None,182 Err(Error::Revert(e)) => Err(PrecompileFailure::Revert {183 exit_status: ExitRevert::Reverted,184 output: (&e as &str,).abi_encode_call(evm_coder::fn_selector!(Error(string))),185 }),186 Err(Error::Fatal(f)) => Err(PrecompileFailure::Fatal { exit_status: f }),187 Err(Error::Error(e)) => Err(e.into()),188 })189 }190191 192 pub fn consume_store_reads(&self, reads: u64) -> execution::Result<()> {193 self.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(194 <T as frame_system::Config>::DbWeight::get()195 .read196 .saturating_mul(reads),197 198 0,199 )))200 }201202 203 pub fn consume_store_writes(&self, writes: u64) -> execution::Result<()> {204 self.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(205 <T as frame_system::Config>::DbWeight::get()206 .write207 .saturating_mul(writes),208 209 0,210 )))211 }212213 214 pub fn consume_store_reads_and_writes(&self, reads: u64, writes: u64) -> execution::Result<()> {215 let weight = <T as frame_system::Config>::DbWeight::get();216 let reads = weight.read.saturating_mul(reads);217 let writes = weight.read.saturating_mul(writes);218 self.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(219 reads.saturating_add(writes),220 221 0,222 )))223 }224}225226pub fn dispatch_to_evm<T: Config>(err: DispatchError) -> execution::Error {227 use execution::Error as ExError;228 match err {229 DispatchError::Module(ModuleError { index, error, .. })230 if index231 == T::PalletInfo::index::<Pallet<T>>()232 .expect("evm-coder-substrate is a pallet, which should be added to runtime")233 as u8 =>234 {235 let mut read = &error as &[u8];236 match Error::<T>::decode(&mut read) {237 Ok(Error::<T>::OutOfGas) => ExError::Error(ExitError::OutOfGas),238 Ok(Error::<T>::OutOfFund) => ExError::Error(ExitError::OutOfFund),239 _ => unreachable!("this pallet only defines two possible errors"),240 }241 }242 DispatchError::Module(ModuleError {243 message: Some(msg), ..244 }) => ExError::Revert(msg.into()),245 DispatchError::Module(ModuleError { index, error, .. }) => {246 ExError::Revert(format!("error {error:?} in pallet {index}"))247 }248 e => ExError::Revert(format!("substrate error: {e:?}")),249 }250}251252pub trait WithRecorder<T: Config> {253 fn recorder(&self) -> &SubstrateRecorder<T>;254 fn into_recorder(self) -> SubstrateRecorder<T>;255}256257258pub fn call<T, C, E, H>(handle: &mut H, mut e: E) -> Option<PrecompileResult>259where260 T: Config,261 C: evm_coder::Call + PreDispatch,262 E: evm_coder::Callable<C> + WithRecorder<T>,263 H: PrecompileHandle,264 execution::ResultWithPostInfo<Vec<u8>>: From<ResultWithPostInfoOf<E, Vec<u8>>>,265{266 let result = call_internal(267 handle.context().caller,268 &mut e,269 handle.context().apparent_value,270 handle.input(),271 );272 e.into_recorder().evm_to_precompile_output(handle, result)273}274275fn call_internal<T, C, E>(276 caller: H160,277 e: &mut E,278 value: Value,279 input: &[u8],280) -> execution::Result<Option<Vec<u8>>>281where282 T: Config,283 C: evm_coder::Call + PreDispatch,284 E: Contract + evm_coder::Callable<C> + WithRecorder<T>,285 execution::ResultWithPostInfo<Vec<u8>>: From<ResultWithPostInfoOf<E, Vec<u8>>>,286{287 let call = C::parse_full(input)?;288 if call.is_none() {289 return Err("unrecognized selector".into());290 }291 let call = call.unwrap();292293 let dispatch_info = call.dispatch_info();294 e.recorder()295 .consume_gas(T::GasWeightMapping::weight_to_gas(dispatch_info.weight))?;296297 match execution::ResultWithPostInfo::from(e.call(Msg {298 call,299 caller,300 value,301 })) {302 Ok(v) => {303 let unspent = v.post_info.calc_unspent(&dispatch_info);304 e.recorder()305 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));306 Ok(Some(v.data))307 }308 Err(v) => {309 let unspent = v.post_info.calc_unspent(&dispatch_info);310 e.recorder()311 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));312 Err(v.data)313 }314 }315}316317#[cfg(test)]318#[allow(dead_code)]319mod tests {320 use core::marker::PhantomData;321322 use evm_coder::ERC165Call;323 use frame_support::weights::Weight;324325 use crate::execution::PreDispatch;326327 #[derive(PreDispatch)]328 enum ExampleCall<T: super::Config> {329 ERC165Call(ERC165Call, PhantomData<fn() -> T>),330 OtherCall(ERC165Call),331332 #[weight(Weight::from_ref_time(a + b))]333 Example {334 a: u64,335 b: u64,336 },337 }338}