1#![cfg_attr(not(feature = "std"), no_std)]23#[cfg(not(feature = "std"))]4extern crate alloc;56pub use pallet::*;78#[frame_support::pallet]9pub mod pallet {10 #[cfg(not(feature = "std"))]11 use alloc::format;1213 use evm_coder::{14 ToLog,15 abi::{AbiReader, AbiWrite, AbiWriter},16 execution::{self, Result},17 types::{Msg, value},18 };19 use frame_support::ensure;20 use pallet_evm::{ExitError, ExitReason, ExitRevert, ExitSucceed, PrecompileOutput};21 pub use frame_support::dispatch::DispatchResult;22 use pallet_ethereum::EthereumTransactionSender;23 use sp_std::cell::RefCell;24 use sp_std::vec::Vec;25 use sp_core::{H160, H256};26 use ethereum::Log;27 use frame_support::{pallet_prelude::*, traits::PalletInfo};2829 30 31 32 33 34 #[pallet::error]35 pub enum Error<T> {36 OutOfGas,37 OutOfFund,38 }3940 #[pallet::config]41 pub trait Config: frame_system::Config {42 type EthereumTransactionSender: pallet_ethereum::EthereumTransactionSender;43 }4445 #[pallet::pallet]46 pub struct Pallet<T>(_);4748 49 pub const G_LOG: u64 = 375;50 pub const G_LOGDATA: u64 = 8;51 pub const G_LOGTOPIC: u64 = 375;5253 54 pub const G_SLOAD_WORD: u64 = 800;55 pub const G_SSTORE_WORD: u64 = 20000;5657 fn log_price(data: usize, topics: usize) -> u64 {58 G_LOG59 .saturating_add((data as u64).saturating_mul(G_LOGDATA))60 .saturating_add((topics as u64).saturating_mul(G_LOGTOPIC))61 }6263 pub fn generate_transaction() -> ethereum::TransactionV0 {64 use ethereum::{TransactionV0, TransactionAction, TransactionSignature};65 TransactionV0 {66 nonce: 0.into(),67 gas_price: 0.into(),68 gas_limit: 0.into(),69 action: TransactionAction::Call(H160([0; 20])),70 value: 0.into(),71 72 input: Vec::from([0, 0, 0, 0]),73 74 signature: TransactionSignature::new(27, H256([0x88; 32]), H256([0x88; 32])).unwrap(),75 }76 }7778 #[derive(Default)]79 pub struct SubstrateRecorder<T: Config> {80 contract: H160,81 logs: RefCell<Vec<Log>>,82 initial_gas: u64,83 gas_limit: RefCell<u64>,84 _phantom: PhantomData<*const T>,85 }8687 impl<T: Config> SubstrateRecorder<T> {88 pub fn new(contract: H160, gas_limit: u64) -> Self {89 Self {90 contract,91 logs: RefCell::new(Vec::new()),92 initial_gas: gas_limit,93 gas_limit: RefCell::new(gas_limit),94 _phantom: PhantomData,95 }96 }9798 pub fn is_empty(&self) -> bool {99 self.logs.borrow().is_empty()100 }101 pub fn log_sub(&self, log: impl ToLog) -> DispatchResult {102 self.log_raw_sub(log.to_log(self.contract))103 }104 pub fn log_raw_sub(&self, log: Log) -> DispatchResult {105 self.consume_gas_sub(log_price(log.data.len(), log.topics.len()))?;106 self.logs.borrow_mut().push(log);107 Ok(())108 }109 pub fn retrieve_logs(self) -> Vec<Log> {110 self.logs.into_inner()111 }112113 pub fn gas_left(&self) -> u64 {114 *self.gas_limit.borrow()115 }116 pub fn consume_sload_sub(&self) -> DispatchResult {117 self.consume_gas_sub(G_SLOAD_WORD)118 }119 pub fn consume_sstore_sub(&self) -> DispatchResult {120 self.consume_gas_sub(G_SSTORE_WORD)121 }122 pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {123 ensure!(gas != u64::MAX, Error::<T>::OutOfGas);124 let mut gas_limit = self.gas_limit.borrow_mut();125 ensure!(gas <= *gas_limit, Error::<T>::OutOfGas);126 *gas_limit -= gas;127 Ok(())128 }129130 pub fn consume_sload(&self) -> Result<()> {131 self.consume_gas(G_SLOAD_WORD)132 }133 pub fn consume_sstore(&self) -> Result<()> {134 self.consume_gas(G_SSTORE_WORD)135 }136 pub fn consume_gas(&self, gas: u64) -> Result<()> {137 if gas == u64::MAX {138 return Err(execution::Error::Error(ExitError::OutOfGas));139 }140 let mut gas_limit = self.gas_limit.borrow_mut();141 if gas > *gas_limit {142 return Err(execution::Error::Error(ExitError::OutOfGas));143 }144 *gas_limit -= gas;145 Ok(())146 }147148 pub fn evm_to_precompile_output(149 self,150 result: evm_coder::execution::Result<Option<AbiWriter>>,151 ) -> Option<PrecompileOutput> {152 use evm_coder::execution::Error;153 let (writer, reason) = match result {154 Ok(Some(v)) => (v, ExitReason::Succeed(ExitSucceed::Returned)),155 Ok(None) => return None,156 Err(Error::Revert(e)) => {157 let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));158 (&e as &str).abi_write(&mut writer);159160 (writer, ExitReason::Revert(ExitRevert::Reverted))161 }162 Err(Error::Fatal(f)) => (AbiWriter::new(), ExitReason::Fatal(f)),163 Err(Error::Error(e)) => (AbiWriter::new(), ExitReason::Error(e)),164 };165166 Some(PrecompileOutput {167 cost: self.initial_gas - self.gas_left(),168 exit_status: reason,169 logs: self.retrieve_logs(),170 output: writer.finish(),171 })172 }173174 pub fn submit_logs(self) -> DispatchResult {175 let logs = self.retrieve_logs();176 if logs.is_empty() {177 return Ok(());178 }179 T::EthereumTransactionSender::submit_logs_transaction(generate_transaction(), logs)180 }181 }182183 pub fn dispatch_to_evm<T: Config>(err: DispatchError) -> evm_coder::execution::Error {184 use evm_coder::execution::Error as ExError;185 match err {186 DispatchError::Module { index, error, .. }187 if index188 == T::PalletInfo::index::<Pallet<T>>()189 .expect("evm-coder-substrate is a pallet, which should be added to runtime")190 as u8 =>191 {192 match error {193 v if v == Error::<T>::OutOfGas.as_u8() => ExError::Error(ExitError::OutOfGas),194 v if v == Error::<T>::OutOfFund.as_u8() => ExError::Error(ExitError::OutOfFund),195 _ => unreachable!("this pallet only defines two possible errors"),196 }197 }198 DispatchError::Module {199 message: Some(msg), ..200 } => ExError::Revert(msg.into()),201 DispatchError::Module { index, error, .. } => {202 ExError::Revert(format!("error {} in pallet {}", error, index))203 }204 e => ExError::Revert(format!("substrate error: {:?}", e)),205 }206 }207208 pub fn call_internal<C: evm_coder::Call, E: evm_coder::Callable<C>>(209 caller: H160,210 e: &mut E,211 value: value,212 input: &[u8],213 ) -> evm_coder::execution::Result<Option<AbiWriter>> {214 let (selector, mut reader) = AbiReader::new_call(input)?;215 let call = C::parse(selector, &mut reader)?;216 if call.is_none() {217 return Ok(None);218 }219 let call = call.unwrap();220 e.call(Msg {221 call,222 caller,223 value,224 })225 .map(Some)226 }227}