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;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 abi::{AbiReader, AbiWrite, AbiWriter},50 types::{Msg, Value},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<AbiWriter>>,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.finish(),180 }),181 Ok(None) => return None,182 Err(Error::Revert(e)) => {183 let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));184 (&e as &str).abi_write(&mut writer);185186 Err(PrecompileFailure::Revert {187 exit_status: ExitRevert::Reverted,188 output: writer.finish(),189 })190 }191 Err(Error::Fatal(f)) => Err(PrecompileFailure::Fatal { exit_status: f }),192 Err(Error::Error(e)) => Err(e.into()),193 })194 }195196 197 pub fn consume_store_reads(&self, reads: u64) -> execution::Result<()> {198 self.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(199 <T as frame_system::Config>::DbWeight::get()200 .read201 .saturating_mul(reads),202 203 0,204 )))205 }206207 208 pub fn consume_store_writes(&self, writes: u64) -> execution::Result<()> {209 self.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(210 <T as frame_system::Config>::DbWeight::get()211 .write212 .saturating_mul(writes),213 214 0,215 )))216 }217218 219 pub fn consume_store_reads_and_writes(&self, reads: u64, writes: u64) -> execution::Result<()> {220 let weight = <T as frame_system::Config>::DbWeight::get();221 let reads = weight.read.saturating_mul(reads);222 let writes = weight.read.saturating_mul(writes);223 self.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(224 reads.saturating_add(writes),225 226 0,227 )))228 }229}230231pub fn dispatch_to_evm<T: Config>(err: DispatchError) -> execution::Error {232 use execution::Error as ExError;233 match err {234 DispatchError::Module(ModuleError { index, error, .. })235 if index236 == T::PalletInfo::index::<Pallet<T>>()237 .expect("evm-coder-substrate is a pallet, which should be added to runtime")238 as u8 =>239 {240 let mut read = &error as &[u8];241 match Error::<T>::decode(&mut read) {242 Ok(Error::<T>::OutOfGas) => ExError::Error(ExitError::OutOfGas),243 Ok(Error::<T>::OutOfFund) => ExError::Error(ExitError::OutOfFund),244 _ => unreachable!("this pallet only defines two possible errors"),245 }246 }247 DispatchError::Module(ModuleError {248 message: Some(msg), ..249 }) => ExError::Revert(msg.into()),250 DispatchError::Module(ModuleError { index, error, .. }) => {251 ExError::Revert(format!("error {error:?} in pallet {index}"))252 }253 e => ExError::Revert(format!("substrate error: {e:?}")),254 }255}256257pub trait WithRecorder<T: Config> {258 fn recorder(&self) -> &SubstrateRecorder<T>;259 fn into_recorder(self) -> SubstrateRecorder<T>;260}261262263pub fn call<T, C, E, H>(handle: &mut H, mut e: E) -> Option<PrecompileResult>264where265 T: Config,266 C: evm_coder::Call + PreDispatch,267 E: evm_coder::Callable<C> + WithRecorder<T>,268 H: PrecompileHandle,269 execution::ResultWithPostInfo<AbiWriter>: From<ResultWithPostInfoOf<E, AbiWriter>>,270{271 let result = call_internal(272 handle.context().caller,273 &mut e,274 handle.context().apparent_value,275 handle.input(),276 );277 e.into_recorder().evm_to_precompile_output(handle, result)278}279280fn call_internal<T, C, E>(281 caller: H160,282 e: &mut E,283 value: Value,284 input: &[u8],285) -> execution::Result<Option<AbiWriter>>286where287 T: Config,288 C: evm_coder::Call + PreDispatch,289 E: Contract + evm_coder::Callable<C> + WithRecorder<T>,290 execution::ResultWithPostInfo<AbiWriter>: From<ResultWithPostInfoOf<E, AbiWriter>>,291{292 let (selector, mut reader) = AbiReader::new_call(input)?;293 let call = C::parse(selector, &mut reader)?;294 if call.is_none() {295 let selector = u32::from_be_bytes(selector);296 return Err(format!("unrecognized selector: 0x{selector:0<8x}").into());297 }298 let call = call.unwrap();299300 let dispatch_info = call.dispatch_info();301 e.recorder()302 .consume_gas(T::GasWeightMapping::weight_to_gas(dispatch_info.weight))?;303304 match execution::ResultWithPostInfo::from(e.call(Msg {305 call,306 caller,307 value,308 })) {309 Ok(v) => {310 let unspent = v.post_info.calc_unspent(&dispatch_info);311 e.recorder()312 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));313 Ok(Some(v.data))314 }315 Err(v) => {316 let unspent = v.post_info.calc_unspent(&dispatch_info);317 e.recorder()318 .return_gas(T::GasWeightMapping::weight_to_gas(unspent));319 Err(v.data)320 }321 }322}323324#[cfg(test)]325#[allow(dead_code)]326mod tests {327 use core::marker::PhantomData;328329 use evm_coder::ERC165Call;330 use frame_support::weights::Weight;331332 use crate::execution::PreDispatch;333334 #[derive(PreDispatch)]335 enum ExampleCall<T: super::Config> {336 ERC165Call(ERC165Call, PhantomData<fn() -> T>),337 OtherCall(ERC165Call),338339 #[weight(Weight::from_ref_time(a + b))]340 Example {341 a: u64,342 b: u64,343 },344 }345}