Skip to main content

reth_rpc_eth_types/error/
mod.rs

1//! Implementation specific Errors for the `eth_` namespace.
2
3pub mod api;
4use alloy_eips::BlockId;
5use alloy_primitives::{Address, Bytes, B256, U256};
6use alloy_rpc_types_eth::{error::EthRpcErrorCode, request::TransactionInputError, BlockError};
7use alloy_sol_types::RevertReason;
8use alloy_transport::{RpcError, TransportErrorKind};
9pub use api::{AsEthApiError, FromEthApiError, FromEvmError, IntoEthApiError};
10use core::time::Duration;
11use evm2::{interpreter::InstrStop, registry::HandlerError};
12use evm2_inspectors::tracing::{DebugInspectorError, MuxError};
13use reth_errors::{BlockExecutionError, BlockValidationError, ProviderError, RethError};
14use reth_primitives_traits::transaction::{error::InvalidTransactionError, signed::RecoveryError};
15use reth_rpc_convert::{CallFeesError, EthTxEnvError, TransactionConversionError};
16use reth_rpc_server_types::result::{
17    internal_rpc_err, invalid_params_rpc_err, rpc_err, rpc_error_with_code,
18};
19use reth_transaction_pool::error::{
20    Eip4844PoolTransactionError, Eip7702PoolTransactionError, InvalidPoolTransactionError,
21    PoolError, PoolErrorKind, PoolTransactionError, RawPoolTransactionError,
22};
23use std::convert::Infallible;
24use tokio::sync::oneshot::error::RecvError;
25
26/// A trait to convert an error to an RPC error.
27pub trait ToRpcError: core::error::Error + Send + Sync + 'static {
28    /// Converts the error to a JSON-RPC error object.
29    fn to_rpc_error(&self) -> jsonrpsee_types::ErrorObject<'static>;
30}
31
32impl ToRpcError for jsonrpsee_types::ErrorObject<'static> {
33    fn to_rpc_error(&self) -> jsonrpsee_types::ErrorObject<'static> {
34        self.clone()
35    }
36}
37
38impl ToRpcError for RpcError<TransportErrorKind> {
39    fn to_rpc_error(&self) -> jsonrpsee_types::ErrorObject<'static> {
40        match self {
41            Self::ErrorResp(payload) => jsonrpsee_types::error::ErrorObject::owned(
42                payload.code as i32,
43                payload.message.clone(),
44                payload.data.clone(),
45            ),
46            err => internal_rpc_err(err.to_string()),
47        }
48    }
49}
50
51/// Result alias
52pub type EthResult<T> = Result<T, EthApiError>;
53
54/// Errors that can occur when interacting with the `eth_` namespace
55#[derive(Debug, thiserror::Error)]
56pub enum EthApiError {
57    /// When a raw transaction is empty
58    #[error("empty transaction data")]
59    EmptyRawTransactionData,
60    /// When decoding a signed transaction fails
61    #[error("failed to decode signed transaction")]
62    FailedToDecodeSignedTransaction,
63    /// When the transaction signature is invalid
64    #[error("invalid transaction signature")]
65    InvalidTransactionSignature,
66    /// Errors related to the transaction pool
67    #[error(transparent)]
68    PoolError(#[from] RpcPoolError),
69    /// Header not found for block hash/number/tag
70    #[error("header not found")]
71    HeaderNotFound(BlockId),
72    /// Header range not found for start block hash/number/tag to end block hash/number/tag
73    #[error("header range not found, start block {0:?}, end block {1:?}")]
74    HeaderRangeNotFound(BlockId, BlockId),
75    /// Thrown when historical data is not available because it has been pruned
76    ///
77    /// This error is intended for use as a standard response when historical data is
78    /// requested that has been pruned according to the node's data retention policy.
79    ///
80    /// See also <https://eips.ethereum.org/EIPS/eip-4444>
81    #[error("pruned history unavailable: requested {requested}, earliest available {earliest_available}")]
82    PrunedHistoryUnavailable {
83        /// The requested block number
84        requested: u64,
85        /// The earliest block number that is still available
86        earliest_available: u64,
87    },
88    /// Receipts not found for block hash/number/tag
89    #[error("receipts not found")]
90    ReceiptsNotFound(BlockId),
91    /// Thrown when an unknown block or transaction index is encountered
92    #[error("unknown block or tx index")]
93    UnknownBlockOrTxIndex,
94    /// When an invalid block range is provided
95    #[error("invalid block range")]
96    InvalidBlockRange,
97    /// Requested block number is beyond the head block
98    #[error("request beyond head block: requested {requested}, head {head}")]
99    RequestBeyondHead {
100        /// The requested block number
101        requested: u64,
102        /// The current head block number
103        head: u64,
104    },
105    /// Thrown when the target block for proof computation exceeds the maximum configured window.
106    #[error("distance to target block exceeds maximum proof window")]
107    ExceedsMaxProofWindow,
108    /// An internal error where prevrandao is not set in the evm's environment
109    #[error("prevrandao not in the EVM's environment after merge")]
110    PrevrandaoNotSet,
111    /// `excess_blob_gas` is not set for Cancun and above
112    #[error("excess blob gas missing in the EVM's environment after Cancun")]
113    ExcessBlobGasNotSet,
114    /// Thrown when a call or transaction request (`eth_call`, `eth_estimateGas`,
115    /// `eth_sendTransaction`) contains conflicting fields (legacy, EIP-1559)
116    #[error("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")]
117    ConflictingFeeFieldsInRequest,
118    /// Errors related to invalid transactions
119    #[error(transparent)]
120    InvalidTransaction(#[from] RpcInvalidTransactionError),
121    /// Thrown when constructing an RPC block from primitive block data fails
122    #[error(transparent)]
123    InvalidBlockData(#[from] BlockError),
124    /// Thrown when an `AccountOverride` contains conflicting `state` and `stateDiff` fields
125    #[error("account {0:?} has both 'state' and 'stateDiff'")]
126    BothStateAndStateDiffInOverride(Address),
127    /// Other internal error
128    #[error(transparent)]
129    Internal(RethError),
130    /// Error related to signing
131    #[error(transparent)]
132    Signing(#[from] SignError),
133    /// Thrown when a requested transaction is not found
134    #[error("transaction not found")]
135    TransactionNotFound,
136    /// Thrown when a transaction requested by a tracing method is not found
137    #[error("transaction not found")]
138    TracingTransactionNotFound,
139    /// Thrown when a block requested by a tracing method is not found
140    #[error("block not found")]
141    TracingBlockNotFound(BlockId),
142    /// Thrown when a tracing method is called for the genesis block
143    #[error("genesis is not traceable")]
144    GenesisNotTraceable,
145    /// Some feature is unsupported
146    #[error("unsupported")]
147    Unsupported(&'static str),
148    /// General purpose error for invalid params
149    #[error("{0}")]
150    InvalidParams(String),
151    /// When the tracer config does not match the tracer
152    #[error("invalid tracer config")]
153    InvalidTracerConfig,
154    /// When the percentile array is invalid
155    #[error("invalid reward percentiles")]
156    InvalidRewardPercentiles,
157    /// Error thrown when a spawned blocking task failed to deliver an anticipated response.
158    ///
159    /// This only happens if the blocking task panics and is aborted before it can return a
160    /// response back to the request handler.
161    #[error("internal blocking task error")]
162    InternalBlockingTaskError,
163    /// Error thrown when a spawned blocking task failed to deliver an anticipated response
164    #[error("internal eth error")]
165    InternalEthError,
166    /// Error thrown when a (tracing) call exceeds the configured timeout
167    #[error("execution aborted (timeout = {0:?})")]
168    ExecutionTimedOut(Duration),
169    /// Internal Error thrown by the javascript tracer
170    #[error("{0}")]
171    InternalJsTracerError(String),
172    #[error(transparent)]
173    /// Call Input error when both `data` and `input` fields are set and not equal.
174    TransactionInputError(#[from] TransactionInputError),
175    /// EVM generic purpose error.
176    #[error("EVM error: {0}")]
177    EvmCustom(String),
178    /// Bytecode override is invalid.
179    ///
180    /// This can happen if bytecode provided in an
181    /// [`AccountOverride`](alloy_rpc_types_eth::state::AccountOverride) is malformed, e.g. invalid
182    /// 7702 bytecode.
183    #[error("Invalid bytecode: {0}")]
184    InvalidBytecode(String),
185    /// Error encountered when converting a transaction type
186    #[error(transparent)]
187    TransactionConversionError(#[from] TransactionConversionError),
188    /// Error thrown when tracing with a muxTracer fails
189    #[error("{0}")]
190    MuxTracerError(String),
191    /// Error thrown when waiting for transaction confirmation times out
192    #[error(
193        "Transaction {hash} was added to the mempool but wasn't confirmed within {duration:?}."
194    )]
195    TransactionConfirmationTimeout {
196        /// Hash of the transaction that timed out
197        hash: B256,
198        /// Duration that was waited before timing out
199        duration: Duration,
200    },
201    /// Error thrown when batch tx response channel fails
202    #[error(transparent)]
203    BatchTxRecvError(#[from] RecvError),
204    /// Error thrown when batch tx send channel fails
205    #[error("Batch transaction sender channel closed")]
206    BatchTxSendError,
207    /// Error that occurred during `call_many` execution with bundle and transaction context
208    #[error("call_many error in bundle {bundle_index} and transaction {tx_index}: {}", .error.message())]
209    CallManyError {
210        /// Bundle index where the error occurred
211        bundle_index: usize,
212        /// Transaction index within the bundle where the error occurred
213        tx_index: usize,
214        /// The underlying error object
215        error: jsonrpsee_types::ErrorObject<'static>,
216    },
217    /// Error thrown when trying to access block access list for blocks before Amsterdam
218    #[error("Block access list not available for pre-Amsterdam blocks")]
219    BlockAccessListNotAvailablePreAmsterdam,
220    /// Thrown when the calls of an `eth_callMany`, `trace_callMany` or `debug_traceCallMany`
221    /// request need more gas than the RPC gas cap they share.
222    #[error("the request's calls exceed the RPC gas cap of {0}")]
223    CallManyGasCapExceeded(u64),
224    /// Any other error
225    #[error("{0}")]
226    Other(Box<dyn ToRpcError>),
227}
228
229/// Insufficient funds error.
230#[derive(Debug, thiserror::Error)]
231#[error("insufficient funds: cost {cost} > balance {balance}")]
232pub struct InsufficientFundsError {
233    /// Transaction cost.
234    pub cost: U256,
235    /// Account balance.
236    pub balance: U256,
237}
238
239/// Error type for call utilities.
240#[derive(Debug, thiserror::Error)]
241pub enum CallError<E> {
242    /// Database error.
243    #[error(transparent)]
244    Database(E),
245    /// Insufficient funds error.
246    #[error(transparent)]
247    InsufficientFunds(#[from] InsufficientFundsError),
248}
249
250/// Errors that can occur while applying state overrides.
251#[derive(Debug, thiserror::Error)]
252pub enum StateOverrideError<E> {
253    /// Invalid bytecode provided in an override.
254    #[error(transparent)]
255    InvalidBytecode(#[from] evm2::bytecode::BytecodeDecodeError),
256    /// Both state and state diff were provided for an account.
257    #[error("Both 'state' and 'stateDiff' fields are set for account {0}")]
258    BothStateAndStateDiff(Address),
259    /// Database error.
260    #[error(transparent)]
261    Database(E),
262}
263
264impl EthApiError {
265    /// Creates a new [`EthApiError::Other`] variant.
266    pub fn other<E: ToRpcError>(err: E) -> Self {
267        Self::Other(Box::new(err))
268    }
269
270    /// Creates a new [`EthApiError::CallManyError`] variant.
271    pub const fn call_many_error(
272        bundle_index: usize,
273        tx_index: usize,
274        error: jsonrpsee_types::ErrorObject<'static>,
275    ) -> Self {
276        Self::CallManyError { bundle_index, tx_index, error }
277    }
278
279    /// Returns `true` if error is [`RpcInvalidTransactionError::GasTooHigh`]
280    pub const fn is_gas_too_high(&self) -> bool {
281        matches!(
282            self,
283            Self::InvalidTransaction(
284                RpcInvalidTransactionError::GasTooHigh |
285                    RpcInvalidTransactionError::GasLimitTooHigh
286            )
287        )
288    }
289
290    /// Returns `true` if error is [`RpcInvalidTransactionError::GasTooLow`]
291    pub const fn is_gas_too_low(&self) -> bool {
292        matches!(self, Self::InvalidTransaction(RpcInvalidTransactionError::GasTooLow))
293    }
294
295    /// Returns the [`RpcInvalidTransactionError`] if this is a [`EthApiError::InvalidTransaction`]
296    pub const fn as_invalid_transaction(&self) -> Option<&RpcInvalidTransactionError> {
297        match self {
298            Self::InvalidTransaction(e) => Some(e),
299            _ => None,
300        }
301    }
302
303    /// Converts the given [`StateOverrideError`] into a new [`EthApiError`] instance.
304    pub fn from_state_overrides_err<E>(err: StateOverrideError<E>) -> Self
305    where
306        E: Into<Self>,
307    {
308        err.into()
309    }
310
311    /// Converts the given [`CallError`] into a new [`EthApiError`] instance.
312    pub fn from_call_err<E>(err: CallError<E>) -> Self
313    where
314        E: Into<Self>,
315    {
316        err.into()
317    }
318
319    /// Converts this error into the rpc error object.
320    pub fn into_rpc_err(self) -> jsonrpsee_types::error::ErrorObject<'static> {
321        self.into()
322    }
323}
324
325impl From<EthApiError> for jsonrpsee_types::error::ErrorObject<'static> {
326    fn from(error: EthApiError) -> Self {
327        match error {
328            EthApiError::FailedToDecodeSignedTransaction |
329            EthApiError::InvalidTransactionSignature |
330            EthApiError::EmptyRawTransactionData |
331            EthApiError::InvalidBlockRange |
332            EthApiError::RequestBeyondHead { .. } |
333            EthApiError::ConflictingFeeFieldsInRequest |
334            EthApiError::Signing(_) |
335            EthApiError::BothStateAndStateDiffInOverride(_) |
336            EthApiError::InvalidTracerConfig |
337            EthApiError::TransactionConversionError(_) |
338            EthApiError::InvalidRewardPercentiles |
339            EthApiError::InvalidBytecode(_) => invalid_params_rpc_err(error.to_string()),
340            EthApiError::InvalidTransaction(err) => err.into(),
341            EthApiError::PoolError(err) => err.into(),
342            EthApiError::Internal(RethError::Provider(
343                reth_errors::ProviderError::StateAtBlockPruned(_),
344            )) => rpc_error_with_code(EthRpcErrorCode::PrunedHistory.code(), error.to_string()),
345            EthApiError::PrevrandaoNotSet |
346            EthApiError::ExcessBlobGasNotSet |
347            EthApiError::InvalidBlockData(_) |
348            EthApiError::Internal(_) |
349            EthApiError::EvmCustom(_) => internal_rpc_err(error.to_string()),
350            EthApiError::UnknownBlockOrTxIndex |
351            EthApiError::TransactionNotFound |
352            EthApiError::BlockAccessListNotAvailablePreAmsterdam => {
353                rpc_error_with_code(EthRpcErrorCode::ResourceNotFound.code(), error.to_string())
354            }
355            EthApiError::TracingTransactionNotFound | EthApiError::GenesisNotTraceable => {
356                rpc_error_with_code(
357                    jsonrpsee_types::error::CALL_EXECUTION_FAILED_CODE,
358                    error.to_string(),
359                )
360            }
361            EthApiError::TracingBlockNotFound(id) => {
362                let id = match id {
363                    BlockId::Hash(hash) => hash.block_hash.to_string(),
364                    BlockId::Number(number) => number.to_string(),
365                };
366                rpc_error_with_code(
367                    jsonrpsee_types::error::CALL_EXECUTION_FAILED_CODE,
368                    format!("block {id} not found"),
369                )
370            }
371            EthApiError::HeaderNotFound(id) | EthApiError::ReceiptsNotFound(id) => {
372                rpc_error_with_code(
373                    EthRpcErrorCode::ResourceNotFound.code(),
374                    format!("block not found: {id}"),
375                )
376            }
377            EthApiError::HeaderRangeNotFound(start_id, end_id) => rpc_error_with_code(
378                EthRpcErrorCode::ResourceNotFound.code(),
379                format!("{error}: start block: {start_id}, end block: {end_id}"),
380            ),
381            err @ EthApiError::TransactionConfirmationTimeout { .. } => rpc_error_with_code(
382                EthRpcErrorCode::TransactionConfirmationTimeout.code(),
383                err.to_string(),
384            ),
385            EthApiError::Unsupported(msg) => internal_rpc_err(msg),
386            EthApiError::InternalJsTracerError(msg) | EthApiError::MuxTracerError(msg) => {
387                internal_rpc_err(msg)
388            }
389            EthApiError::InvalidParams(msg) => invalid_params_rpc_err(msg),
390            err @ (EthApiError::ExecutionTimedOut(_) | EthApiError::CallManyGasCapExceeded(_)) => {
391                rpc_error_with_code(
392                    jsonrpsee_types::error::CALL_EXECUTION_FAILED_CODE,
393                    err.to_string(),
394                )
395            }
396            err @ (EthApiError::InternalBlockingTaskError | EthApiError::InternalEthError) => {
397                internal_rpc_err(err.to_string())
398            }
399            err @ EthApiError::TransactionInputError(_) => invalid_params_rpc_err(err.to_string()),
400            EthApiError::PrunedHistoryUnavailable { .. } | EthApiError::ExceedsMaxProofWindow => {
401                rpc_error_with_code(EthRpcErrorCode::PrunedHistory.code(), error.to_string())
402            }
403            EthApiError::Other(err) => err.to_rpc_error(),
404            EthApiError::BatchTxRecvError(err) => internal_rpc_err(err.to_string()),
405            EthApiError::BatchTxSendError => {
406                internal_rpc_err("Batch transaction sender channel closed".to_string())
407            }
408            EthApiError::CallManyError { bundle_index, tx_index, error } => {
409                jsonrpsee_types::error::ErrorObject::owned(
410                    error.code(),
411                    format!(
412                        "call_many error in bundle {bundle_index} and transaction {tx_index}: {}",
413                        error.message()
414                    ),
415                    error.data(),
416                )
417            }
418        }
419    }
420}
421
422impl<E> From<CallError<E>> for EthApiError
423where
424    E: Into<Self>,
425{
426    fn from(value: CallError<E>) -> Self {
427        match value {
428            CallError::Database(err) => err.into(),
429            CallError::InsufficientFunds(insufficient_funds_error) => {
430                Self::InvalidTransaction(RpcInvalidTransactionError::InsufficientFunds {
431                    cost: insufficient_funds_error.cost,
432                    balance: insufficient_funds_error.balance,
433                })
434            }
435        }
436    }
437}
438
439impl<E> From<StateOverrideError<E>> for EthApiError
440where
441    E: Into<Self>,
442{
443    fn from(value: StateOverrideError<E>) -> Self {
444        match value {
445            StateOverrideError::InvalidBytecode(bytecode_decode_error) => {
446                Self::InvalidBytecode(bytecode_decode_error.to_string())
447            }
448            StateOverrideError::BothStateAndStateDiff(address) => {
449                Self::BothStateAndStateDiffInOverride(address)
450            }
451            StateOverrideError::Database(err) => err.into(),
452        }
453    }
454}
455
456impl From<EthTxEnvError> for EthApiError {
457    fn from(value: EthTxEnvError) -> Self {
458        match value {
459            EthTxEnvError::CallFees(CallFeesError::BlobTransactionMissingBlobHashes) => {
460                Self::InvalidTransaction(
461                    RpcInvalidTransactionError::BlobTransactionMissingBlobHashes,
462                )
463            }
464            EthTxEnvError::CallFees(CallFeesError::FeeCapTooLow) => {
465                Self::InvalidTransaction(RpcInvalidTransactionError::FeeCapTooLow)
466            }
467            EthTxEnvError::CallFees(CallFeesError::ConflictingFeeFieldsInRequest) => {
468                Self::ConflictingFeeFieldsInRequest
469            }
470            EthTxEnvError::CallFees(CallFeesError::TipAboveFeeCap) => {
471                Self::InvalidTransaction(RpcInvalidTransactionError::TipAboveFeeCap)
472            }
473            EthTxEnvError::CallFees(CallFeesError::TipVeryHigh) => {
474                Self::InvalidTransaction(RpcInvalidTransactionError::TipVeryHigh)
475            }
476            EthTxEnvError::Input(err) => Self::TransactionInputError(err),
477            EthTxEnvError::BlobTransactionIsCreate => {
478                Self::InvalidTransaction(RpcInvalidTransactionError::BlobTransactionIsCreate)
479            }
480            EthTxEnvError::AuthorizationListInvalidFields => {
481                Self::InvalidTransaction(RpcInvalidTransactionError::AuthorizationListInvalidFields)
482            }
483        }
484    }
485}
486
487#[cfg(feature = "js-tracer")]
488impl From<evm2_inspectors::tracing::js::JsInspectorError> for EthApiError {
489    fn from(error: evm2_inspectors::tracing::js::JsInspectorError) -> Self {
490        match error {
491            err @ evm2_inspectors::tracing::js::JsInspectorError::JsError(_) => {
492                Self::InternalJsTracerError(err.to_string())
493            }
494            err => Self::InvalidParams(err.to_string()),
495        }
496    }
497}
498
499impl From<MuxError> for EthApiError {
500    fn from(error: MuxError) -> Self {
501        Self::MuxTracerError(error.to_string())
502    }
503}
504
505impl From<DebugInspectorError> for EthApiError {
506    fn from(error: DebugInspectorError) -> Self {
507        match error {
508            DebugInspectorError::InvalidTracerConfig(_) => Self::InvalidTracerConfig,
509            DebugInspectorError::UnsupportedTracer => Self::Unsupported("unsupported tracer"),
510            DebugInspectorError::JsTracerNotEnabled => {
511                Self::Unsupported("JS Tracer is not enabled")
512            }
513            DebugInspectorError::MuxInspector(err) => err.into(),
514            DebugInspectorError::Database(err) => Self::Internal(RethError::other(err)),
515            #[cfg(feature = "js-tracer")]
516            DebugInspectorError::JsInspector(err) => err.into(),
517            #[allow(unreachable_patterns)]
518            _ => Self::Unsupported("unsupported tracer error"),
519        }
520    }
521}
522
523impl From<RethError> for EthApiError {
524    fn from(error: RethError) -> Self {
525        match error {
526            RethError::Provider(err) => err.into(),
527            err => Self::Internal(err),
528        }
529    }
530}
531
532impl From<BlockExecutionError> for EthApiError {
533    fn from(error: BlockExecutionError) -> Self {
534        match error {
535            BlockExecutionError::Validation(validation_error) => match validation_error {
536                BlockValidationError::InvalidTx { error, .. } => {
537                    if let Some(invalid_tx) =
538                        error.as_any().downcast_ref::<InvalidTransactionError>()
539                    {
540                        Self::InvalidTransaction(RpcInvalidTransactionError::from(
541                            invalid_tx.clone(),
542                        ))
543                    } else if let Some(handler_error) =
544                        error.as_any().downcast_ref::<HandlerError>()
545                    {
546                        Self::InvalidTransaction(handler_error.clone().into())
547                    } else {
548                        Self::InvalidTransaction(RpcInvalidTransactionError::other(
549                            rpc_error_with_code(
550                                EthRpcErrorCode::TransactionRejected.code(),
551                                error.to_string(),
552                            ),
553                        ))
554                    }
555                }
556                BlockValidationError::Other(error) => match error.downcast_ref::<HandlerError>() {
557                    Some(error) => Self::InvalidTransaction(error.clone().into()),
558                    None => Self::Internal(RethError::Execution(BlockExecutionError::Validation(
559                        BlockValidationError::Other(error),
560                    ))),
561                },
562                _ => Self::Internal(RethError::Execution(BlockExecutionError::Validation(
563                    validation_error,
564                ))),
565            },
566            BlockExecutionError::Internal(internal_error) => {
567                Self::Internal(RethError::Execution(BlockExecutionError::Internal(internal_error)))
568            }
569        }
570    }
571}
572
573impl From<evm2::DatabaseError> for EthApiError {
574    fn from(error: evm2::DatabaseError) -> Self {
575        if let Some(err) = error.downcast_ref::<reth_errors::ProviderError>() {
576            return err.clone().into()
577        }
578        Self::EvmCustom(error.to_string())
579    }
580}
581
582impl From<reth_errors::ProviderError> for EthApiError {
583    fn from(error: reth_errors::ProviderError) -> Self {
584        match error {
585            ProviderError::HeaderNotFound(hash) => Self::HeaderNotFound(hash.into()),
586            ProviderError::BlockHashNotFound(hash) | ProviderError::UnknownBlockHash(hash) => {
587                Self::HeaderNotFound(hash.into())
588            }
589            ProviderError::BestBlockNotFound => Self::HeaderNotFound(BlockId::latest()),
590            ProviderError::BlockNumberForTransactionIndexNotFound => Self::UnknownBlockOrTxIndex,
591            ProviderError::FinalizedBlockNotFound => Self::HeaderNotFound(BlockId::finalized()),
592            ProviderError::SafeBlockNotFound => Self::HeaderNotFound(BlockId::safe()),
593            ProviderError::BlockExpired { requested, earliest_available } => {
594                Self::PrunedHistoryUnavailable { requested, earliest_available }
595            }
596            ProviderError::InsufficientChangesets { requested, available }
597                if requested < *available.start() =>
598            {
599                Self::PrunedHistoryUnavailable { requested, earliest_available: *available.start() }
600            }
601            err => Self::Internal(err.into()),
602        }
603    }
604}
605
606impl From<RecoveryError> for EthApiError {
607    fn from(_: RecoveryError) -> Self {
608        Self::InvalidTransactionSignature
609    }
610}
611
612impl From<RawPoolTransactionError> for EthApiError {
613    fn from(err: RawPoolTransactionError) -> Self {
614        match err {
615            RawPoolTransactionError::EmptyRawTransactionData => Self::EmptyRawTransactionData,
616            RawPoolTransactionError::FailedToDecodeSignedTransaction => {
617                Self::FailedToDecodeSignedTransaction
618            }
619            RawPoolTransactionError::InvalidTransactionSignature => {
620                Self::InvalidTransactionSignature
621            }
622            RawPoolTransactionError::Other(err) => Self::PoolError(RpcPoolError::Other(err)),
623        }
624    }
625}
626
627impl From<Infallible> for EthApiError {
628    fn from(_: Infallible) -> Self {
629        unreachable!()
630    }
631}
632
633/// An error due to invalid transaction.
634///
635/// The only reason this exists is to maintain compatibility with other clients de-facto standard
636/// error messages.
637///
638/// These error variants can be thrown when the transaction is checked prior to execution.
639///
640/// These variants also cover execution-layer transaction validation errors.
641///
642/// ## Nomenclature
643///
644/// This type is explicitly modeled after geth's error variants and uses
645///   `fee cap` for `max_fee_per_gas`
646///   `tip` for `max_priority_fee_per_gas`
647#[derive(thiserror::Error, Debug)]
648pub enum RpcInvalidTransactionError {
649    /// returned if the nonce of a transaction is lower than the one present in the local chain.
650    #[error("nonce too low: next nonce {state}, tx nonce {tx}")]
651    NonceTooLow {
652        /// The nonce of the transaction.
653        tx: u64,
654        /// The current state of the nonce in the local chain.
655        state: u64,
656    },
657    /// returned if the nonce of a transaction is higher than the next one expected based on the
658    /// local chain.
659    #[error("nonce too high")]
660    NonceTooHigh,
661    /// Returned if the nonce of a transaction is too high
662    /// Incrementing the nonce would lead to invalid state (overflow)
663    #[error("nonce has max value")]
664    NonceMaxValue,
665    /// thrown if the transaction sender doesn't have enough funds for a transfer
666    #[error("insufficient funds for transfer")]
667    InsufficientFundsForTransfer,
668    /// thrown if creation transaction provides the init code bigger than init code size limit.
669    #[error("max initcode size exceeded")]
670    MaxInitCodeSizeExceeded,
671    /// Represents the inability to cover max fee + value (account balance too low).
672    #[error("insufficient funds for gas * price + value: have {balance} want {cost}")]
673    InsufficientFunds {
674        /// Transaction cost.
675        cost: U256,
676        /// Current balance of transaction sender.
677        balance: U256,
678    },
679    /// This is similar to [`Self::InsufficientFunds`] but with a different error message and
680    /// exists for compatibility reasons.
681    ///
682    /// This error is used in `eth_estimateCall` when the highest available gas limit, capped with
683    /// the allowance of the caller is too low: [`Self::GasTooLow`].
684    #[error("gas required exceeds allowance ({gas_limit})")]
685    GasRequiredExceedsAllowance {
686        /// The gas limit the transaction was executed with.
687        gas_limit: u64,
688    },
689    /// Thrown when calculating gas usage
690    #[error("gas uint64 overflow")]
691    GasUintOverflow,
692    /// Thrown if the transaction is specified to use less gas than required to start the
693    /// invocation.
694    #[error("intrinsic gas too low")]
695    GasTooLow,
696    /// Thrown if the transaction gas exceeds the limit
697    #[error("intrinsic gas too high")]
698    GasTooHigh,
699    /// Thrown if the transaction gas limit exceeds the maximum
700    #[error("gas limit too high")]
701    GasLimitTooHigh,
702    /// Thrown if a transaction is not supported in the current network configuration.
703    #[error("transaction type not supported")]
704    TxTypeNotSupported,
705    /// Thrown to ensure no one is able to specify a transaction with a tip higher than the total
706    /// fee cap.
707    #[error("max priority fee per gas higher than max fee per gas")]
708    TipAboveFeeCap,
709    /// A sanity error to avoid huge numbers specified in the tip field.
710    #[error("max priority fee per gas higher than 2^256-1")]
711    TipVeryHigh,
712    /// A sanity error to avoid huge numbers specified in the fee cap field.
713    #[error("max fee per gas higher than 2^256-1")]
714    FeeCapVeryHigh,
715    /// Thrown post London if the transaction's fee is less than the base fee of the block
716    #[error("max fee per gas less than block base fee")]
717    FeeCapTooLow,
718    /// Thrown if the sender of a transaction is a contract.
719    #[error("sender is not an EOA")]
720    SenderNoEOA,
721    /// Gas limit was exceeded during execution.
722    /// Contains the gas limit.
723    #[error("out of gas: gas required exceeds: {0}")]
724    BasicOutOfGas(u64),
725    /// Gas limit was exceeded during memory expansion.
726    /// Contains the gas limit.
727    #[error("out of gas: gas exhausted during memory expansion: {0}")]
728    MemoryOutOfGas(u64),
729    /// Memory limit was exceeded during memory expansion.
730    #[error("out of memory: memory limit exceeded during memory expansion")]
731    MemoryLimitOutOfGas,
732    /// Gas limit was exceeded during precompile execution.
733    /// Contains the gas limit.
734    #[error("out of gas: gas exhausted during precompiled contract execution: {0}")]
735    PrecompileOutOfGas(u64),
736    /// An operand to an opcode was invalid or out of range.
737    /// Contains the gas limit.
738    #[error("out of gas: invalid operand to an opcode: {0}")]
739    InvalidOperandOutOfGas(u64),
740    /// Thrown if executing a transaction failed during estimate/call
741    #[error(transparent)]
742    Revert(RevertError),
743    /// Unspecific EVM halt error.
744    #[error("EVM error: {0}")]
745    EvmHalt(String),
746    /// Invalid chain id set for the transaction.
747    #[error("invalid chain ID")]
748    InvalidChainId,
749    /// The transaction is before Spurious Dragon and has a chain ID
750    #[error("transactions before Spurious Dragon should not have a chain ID")]
751    OldLegacyChainId,
752    /// The transaction is before Berlin and has access list
753    #[error("transactions before Berlin should not have access list")]
754    AccessListNotSupported,
755    /// `max_fee_per_blob_gas` is not supported for blocks before the Cancun hardfork.
756    #[error("max_fee_per_blob_gas is not supported for blocks before the Cancun hardfork")]
757    MaxFeePerBlobGasNotSupported,
758    /// `blob_hashes`/`blob_versioned_hashes` is not supported for blocks before the Cancun
759    /// hardfork.
760    #[error("blob_versioned_hashes is not supported for blocks before the Cancun hardfork")]
761    BlobVersionedHashesNotSupported,
762    /// Block `blob_base_fee` is greater than tx-specified `max_fee_per_blob_gas` after Cancun.
763    #[error("max fee per blob gas less than block blob gas fee")]
764    BlobFeeCapTooLow,
765    /// Blob transaction has a versioned hash with an invalid blob
766    #[error("blob hash version mismatch")]
767    BlobHashVersionMismatch,
768    /// Blob transaction has no versioned hashes
769    #[error("blob transaction missing blob hashes")]
770    BlobTransactionMissingBlobHashes,
771    /// Blob transaction has too many blobs
772    #[error("blob transaction exceeds max blobs per block; got {have}")]
773    TooManyBlobs {
774        /// The number of blobs in the transaction.
775        have: usize,
776    },
777    /// Blob transaction is a create transaction
778    #[error("blob transaction is a create transaction")]
779    BlobTransactionIsCreate,
780    /// EIP-7702 is not enabled.
781    #[error("EIP-7702 authorization list not supported")]
782    AuthorizationListNotSupported,
783    /// EIP-7702 transaction has invalid fields set.
784    #[error("EIP-7702 authorization list has invalid fields")]
785    AuthorizationListInvalidFields,
786    /// Transaction priority fee is below the minimum required priority fee.
787    #[error("transaction priority fee below minimum required priority fee {minimum_priority_fee}")]
788    PriorityFeeBelowMinimum {
789        /// Minimum required priority fee.
790        minimum_priority_fee: u128,
791    },
792    /// Any other error
793    #[error("{0}")]
794    Other(Box<dyn ToRpcError>),
795}
796
797impl RpcInvalidTransactionError {
798    /// Creates a new [`RpcInvalidTransactionError::Other`] variant.
799    pub fn other<E: ToRpcError>(err: E) -> Self {
800        Self::Other(Box::new(err))
801    }
802
803    /// Converts the halt error.
804    pub fn halt(reason: InstrStop, gas_limit: u64) -> Self {
805        match reason {
806            InstrStop::OutOfGas | InstrStop::ReentrancySentryOOG => Self::BasicOutOfGas(gas_limit),
807            InstrStop::MemoryOOG => Self::MemoryOutOfGas(gas_limit),
808            InstrStop::MemoryLimitOOG => Self::MemoryLimitOutOfGas,
809            InstrStop::PrecompileOOG => Self::PrecompileOutOfGas(gas_limit),
810            InstrStop::InvalidOperandOOG => Self::InvalidOperandOutOfGas(gas_limit),
811            InstrStop::NonceOverflow => Self::NonceMaxValue,
812            err => Self::EvmHalt(format!("{err:?}")),
813        }
814    }
815
816    /// Returns the rpc error code for this error.
817    pub const fn error_code(&self) -> i32 {
818        match self {
819            Self::InvalidChainId |
820            Self::GasTooLow |
821            Self::GasTooHigh |
822            Self::GasRequiredExceedsAllowance { .. } |
823            Self::NonceTooLow { .. } |
824            Self::NonceTooHigh { .. } |
825            Self::FeeCapTooLow |
826            Self::FeeCapVeryHigh => EthRpcErrorCode::InvalidInput.code(),
827            Self::Revert(_) => EthRpcErrorCode::ExecutionError.code(),
828            _ => EthRpcErrorCode::TransactionRejected.code(),
829        }
830    }
831
832    /// Converts this error into the rpc error object.
833    pub fn into_rpc_err(self) -> jsonrpsee_types::error::ErrorObject<'static> {
834        self.into()
835    }
836}
837
838impl From<RpcInvalidTransactionError> for jsonrpsee_types::error::ErrorObject<'static> {
839    fn from(err: RpcInvalidTransactionError) -> Self {
840        match err {
841            RpcInvalidTransactionError::Revert(revert) => {
842                rpc_err(revert.error_code(), revert.to_string(), Some(revert.output.as_ref()))
843            }
844            RpcInvalidTransactionError::Other(err) => err.to_rpc_error(),
845            err => rpc_err(err.error_code(), err.to_string(), None),
846        }
847    }
848}
849
850impl From<InvalidTransactionError> for RpcInvalidTransactionError {
851    fn from(err: InvalidTransactionError) -> Self {
852        // This conversion is used to convert any transaction errors that could occur inside the
853        // txpool (e.g. `eth_sendRawTransaction`) to their corresponding RPC
854        match err {
855            InvalidTransactionError::InsufficientFunds(res) => {
856                Self::InsufficientFunds { cost: res.expected, balance: res.got }
857            }
858            InvalidTransactionError::NonceNotConsistent { tx, state } => {
859                Self::NonceTooLow { tx, state }
860            }
861            InvalidTransactionError::OldLegacyChainId => {
862                // Note: this should be unreachable since Spurious Dragon now enabled
863                Self::OldLegacyChainId
864            }
865            InvalidTransactionError::ChainIdMismatch => Self::InvalidChainId,
866            InvalidTransactionError::Eip2930Disabled |
867            InvalidTransactionError::Eip1559Disabled |
868            InvalidTransactionError::Eip4844Disabled |
869            InvalidTransactionError::Eip7702Disabled |
870            InvalidTransactionError::TxTypeNotSupported => Self::TxTypeNotSupported,
871            InvalidTransactionError::GasUintOverflow => Self::GasUintOverflow,
872            InvalidTransactionError::GasTooLow => Self::GasTooLow,
873            InvalidTransactionError::GasTooHigh => Self::GasTooHigh,
874            InvalidTransactionError::TipAboveFeeCap => Self::TipAboveFeeCap,
875            InvalidTransactionError::FeeCapTooLow => Self::FeeCapTooLow,
876            InvalidTransactionError::SignerAccountHasBytecode => Self::SenderNoEOA,
877            InvalidTransactionError::GasLimitTooHigh => Self::GasLimitTooHigh,
878        }
879    }
880}
881
882impl From<HandlerError> for RpcInvalidTransactionError {
883    fn from(err: HandlerError) -> Self {
884        match err {
885            HandlerError::InvalidNonce { expected, got } if got < expected => {
886                Self::NonceTooLow { tx: got, state: expected }
887            }
888            HandlerError::InvalidNonce { .. } => Self::NonceTooHigh,
889            HandlerError::InvalidChainId { .. } | HandlerError::MissingChainId => {
890                Self::InvalidChainId
891            }
892            HandlerError::IntrinsicGasTooLow { .. } | HandlerError::GasLimitBelowFloor { .. } => {
893                Self::GasTooLow
894            }
895            HandlerError::InsufficientFunds { fee, balance } => {
896                Self::InsufficientFunds { cost: fee, balance }
897            }
898            HandlerError::RejectCallerWithCode => Self::SenderNoEOA,
899            HandlerError::NonceOverflow => Self::NonceMaxValue,
900            HandlerError::GasLimitMoreThanBlock { .. } |
901            HandlerError::TxGasLimitGreaterThanCap { .. } |
902            HandlerError::IntrinsicGasGreaterThanCap { .. } => Self::GasTooHigh,
903            HandlerError::CreateInitCodeSizeLimit { .. } => Self::MaxInitCodeSizeExceeded,
904            HandlerError::UnsupportedTransactionType(_) |
905            HandlerError::WrongTransactionType { .. } => Self::TxTypeNotSupported,
906            HandlerError::FeeCapLessThanBaseFee { .. } => Self::FeeCapTooLow,
907            HandlerError::EmptyAuthorizationList => Self::AuthorizationListInvalidFields,
908            HandlerError::BlobFeeCapLessThanBlobBaseFee { .. } => Self::BlobFeeCapTooLow,
909            HandlerError::EmptyBlobs => Self::BlobTransactionMissingBlobHashes,
910            HandlerError::TooManyBlobs { have, .. } => Self::TooManyBlobs { have },
911            HandlerError::BlobVersionNotSupported => Self::BlobHashVersionMismatch,
912            HandlerError::PriorityFeeGreaterThanMaxFee => Self::TipAboveFeeCap,
913            err => Self::other(rpc_error_with_code(
914                EthRpcErrorCode::TransactionRejected.code(),
915                err.to_string(),
916            )),
917        }
918    }
919}
920
921/// Represents a reverted transaction and its output data.
922///
923/// Displays "execution reverted(: reason)?" if the reason is a string.
924#[derive(Debug, Clone, thiserror::Error)]
925pub struct RevertError {
926    /// The transaction output data
927    output: Bytes,
928}
929
930// === impl RevertError ==
931
932impl RevertError {
933    /// Wraps the output bytes
934    ///
935    /// Note: this is intended to wrap an EVM revert output
936    pub const fn new(output: Bytes) -> Self {
937        Self { output }
938    }
939
940    /// Returns error code to return for this error.
941    pub const fn error_code(&self) -> i32 {
942        EthRpcErrorCode::ExecutionError.code()
943    }
944}
945
946impl std::fmt::Display for RevertError {
947    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
948        f.write_str("execution reverted")?;
949        if !self.output.is_empty() &&
950            let Some(reason) = RevertReason::decode(&self.output)
951        {
952            let error = reason.to_string();
953            let mut error = error.as_str();
954            if reason.is_revert() {
955                // we strip redundant `revert: ` prefix from the revert reason
956                error = error.trim_start_matches("revert: ");
957            }
958            write!(f, ": {error}")?;
959        }
960        Ok(())
961    }
962}
963
964/// A helper error type that's mainly used to mirror `geth` Txpool's error messages
965#[derive(Debug, thiserror::Error)]
966pub enum RpcPoolError {
967    /// When the transaction is already known
968    #[error("already known")]
969    AlreadyKnown,
970    /// When the sender is invalid
971    #[error("invalid sender")]
972    InvalidSender,
973    /// When the transaction is underpriced
974    #[error("transaction underpriced")]
975    Underpriced,
976    /// When the transaction pool is full
977    #[error("txpool is full")]
978    TxPoolOverflow,
979    /// When the replacement transaction is underpriced
980    #[error("replacement transaction underpriced")]
981    ReplaceUnderpriced,
982    /// When the transaction exceeds the block gas limit
983    #[error("exceeds block gas limit")]
984    ExceedsGasLimit,
985    /// When the transaction gas limit exceeds the maximum transaction gas limit
986    #[error("exceeds max transaction gas limit")]
987    MaxTxGasLimitExceeded,
988    /// Thrown when a new transaction is added to the pool, but then immediately discarded to
989    /// respect the tx fee exceeds the configured cap
990    #[error("tx fee ({max_tx_fee_wei} wei) exceeds the configured cap ({tx_fee_cap_wei} wei)")]
991    ExceedsFeeCap {
992        /// max fee in wei of new tx submitted to the pool (e.g. 0.11534 ETH)
993        max_tx_fee_wei: u128,
994        /// configured tx fee cap in wei (e.g. 1.0 ETH)
995        tx_fee_cap_wei: u128,
996    },
997    /// When a negative value is encountered
998    #[error("negative value")]
999    NegativeValue,
1000    /// When oversized data is encountered
1001    #[error("oversized data: transaction size {size}, limit {limit}")]
1002    OversizedData {
1003        /// Size of the transaction/input data that exceeded the limit.
1004        size: usize,
1005        /// Configured limit that was exceeded.
1006        limit: usize,
1007    },
1008    /// When the max initcode size is exceeded
1009    #[error("max initcode size exceeded")]
1010    ExceedsMaxInitCodeSize,
1011    /// Errors related to invalid transactions
1012    #[error(transparent)]
1013    Invalid(#[from] RpcInvalidTransactionError),
1014    /// Custom pool error
1015    #[error(transparent)]
1016    PoolTransactionError(Box<dyn PoolTransactionError>),
1017    /// EIP-4844 related error
1018    #[error(transparent)]
1019    Eip4844(#[from] Eip4844PoolTransactionError),
1020    /// EIP-7702 related error
1021    #[error(transparent)]
1022    Eip7702(#[from] Eip7702PoolTransactionError),
1023    /// Thrown if a conflicting transaction type is already in the pool
1024    ///
1025    /// In other words, thrown if a transaction with the same sender that violates the exclusivity
1026    /// constraint (blob vs normal tx)
1027    #[error("address already reserved")]
1028    AddressAlreadyReserved,
1029    /// Other unspecified error
1030    #[error(transparent)]
1031    Other(Box<dyn core::error::Error + Send + Sync>),
1032}
1033
1034impl From<RpcPoolError> for jsonrpsee_types::error::ErrorObject<'static> {
1035    fn from(error: RpcPoolError) -> Self {
1036        match error {
1037            RpcPoolError::Invalid(err) => err.into(),
1038            RpcPoolError::TxPoolOverflow => {
1039                rpc_error_with_code(EthRpcErrorCode::TransactionRejected.code(), error.to_string())
1040            }
1041            RpcPoolError::AlreadyKnown |
1042            RpcPoolError::InvalidSender |
1043            RpcPoolError::Underpriced |
1044            RpcPoolError::ReplaceUnderpriced |
1045            RpcPoolError::ExceedsGasLimit |
1046            RpcPoolError::MaxTxGasLimitExceeded |
1047            RpcPoolError::ExceedsFeeCap { .. } |
1048            RpcPoolError::NegativeValue |
1049            RpcPoolError::OversizedData { .. } |
1050            RpcPoolError::ExceedsMaxInitCodeSize |
1051            RpcPoolError::PoolTransactionError(_) |
1052            RpcPoolError::Eip4844(_) |
1053            RpcPoolError::Eip7702(_) |
1054            RpcPoolError::AddressAlreadyReserved => {
1055                rpc_error_with_code(EthRpcErrorCode::InvalidInput.code(), error.to_string())
1056            }
1057            RpcPoolError::Other(other) => internal_rpc_err(other.to_string()),
1058        }
1059    }
1060}
1061
1062impl From<PoolError> for RpcPoolError {
1063    fn from(err: PoolError) -> Self {
1064        match err.kind {
1065            PoolErrorKind::ReplacementUnderpriced => Self::ReplaceUnderpriced,
1066            PoolErrorKind::FeeCapBelowMinimumProtocolFeeCap(_) => Self::Underpriced,
1067            PoolErrorKind::SpammerExceededCapacity(_) | PoolErrorKind::DiscardedOnInsert => {
1068                Self::TxPoolOverflow
1069            }
1070            PoolErrorKind::InvalidTransaction(err) => err.into(),
1071            PoolErrorKind::Other(err) => Self::Other(err),
1072            PoolErrorKind::AlreadyImported => Self::AlreadyKnown,
1073            PoolErrorKind::ExistingConflictingTransactionType(_, _) => Self::AddressAlreadyReserved,
1074        }
1075    }
1076}
1077
1078impl From<InvalidPoolTransactionError> for RpcPoolError {
1079    fn from(err: InvalidPoolTransactionError) -> Self {
1080        match err {
1081            InvalidPoolTransactionError::Consensus(err) => Self::Invalid(err.into()),
1082            InvalidPoolTransactionError::ExceedsGasLimit(_, _) => Self::ExceedsGasLimit,
1083            InvalidPoolTransactionError::MaxTxGasLimitExceeded(_, _) => Self::MaxTxGasLimitExceeded,
1084            InvalidPoolTransactionError::ExceedsFeeCap { max_tx_fee_wei, tx_fee_cap_wei } => {
1085                Self::ExceedsFeeCap { max_tx_fee_wei, tx_fee_cap_wei }
1086            }
1087            InvalidPoolTransactionError::ExceedsMaxInitCodeSize(_, _) => {
1088                Self::ExceedsMaxInitCodeSize
1089            }
1090            InvalidPoolTransactionError::IntrinsicGasTooLow => {
1091                Self::Invalid(RpcInvalidTransactionError::GasTooLow)
1092            }
1093            InvalidPoolTransactionError::OversizedData { size, limit } => {
1094                Self::OversizedData { size, limit }
1095            }
1096            InvalidPoolTransactionError::Underpriced => Self::Underpriced,
1097            InvalidPoolTransactionError::Eip2681 => {
1098                Self::Invalid(RpcInvalidTransactionError::NonceMaxValue)
1099            }
1100            InvalidPoolTransactionError::Other(err) => Self::PoolTransactionError(err),
1101            InvalidPoolTransactionError::Eip4844(err) => Self::Eip4844(err),
1102            InvalidPoolTransactionError::Eip7702(err) => Self::Eip7702(err),
1103            InvalidPoolTransactionError::Overdraft { cost, balance } => {
1104                Self::Invalid(RpcInvalidTransactionError::InsufficientFunds { cost, balance })
1105            }
1106            InvalidPoolTransactionError::PriorityFeeBelowMinimum { minimum_priority_fee } => {
1107                Self::Invalid(RpcInvalidTransactionError::PriorityFeeBelowMinimum {
1108                    minimum_priority_fee,
1109                })
1110            }
1111        }
1112    }
1113}
1114
1115impl From<PoolError> for EthApiError {
1116    fn from(err: PoolError) -> Self {
1117        Self::PoolError(RpcPoolError::from(err))
1118    }
1119}
1120
1121/// Errors returned from a sign request.
1122#[derive(Debug, thiserror::Error)]
1123pub enum SignError {
1124    /// Error occurred while trying to sign data.
1125    #[error("could not sign")]
1126    CouldNotSign,
1127    /// Signer for requested account not found.
1128    #[error("unknown account")]
1129    NoAccount,
1130    /// `TypedData` has invalid format.
1131    #[error("given typed data is not valid")]
1132    InvalidTypedData,
1133    /// Invalid transaction request in `sign_transaction`.
1134    #[error("invalid transaction request")]
1135    InvalidTransactionRequest,
1136    /// No chain ID was given.
1137    #[error("no chainid")]
1138    NoChainId,
1139}
1140
1141#[cfg(test)]
1142mod tests {
1143    use super::*;
1144    use alloy_primitives::b256;
1145    use alloy_sol_types::{Revert, SolError};
1146    use reth_errors::ProviderError;
1147
1148    #[test]
1149    fn gas_limit_handler_errors_map_to_gas_errors() {
1150        assert!(matches!(
1151            RpcInvalidTransactionError::from(HandlerError::GasLimitBelowFloor {
1152                required: 2,
1153                got: 1
1154            }),
1155            RpcInvalidTransactionError::GasTooLow
1156        ));
1157        assert!(matches!(
1158            RpcInvalidTransactionError::from(HandlerError::IntrinsicGasGreaterThanCap {
1159                required: 2,
1160                cap: 1
1161            }),
1162            RpcInvalidTransactionError::GasTooHigh
1163        ));
1164    }
1165
1166    #[test]
1167    fn timed_out_error() {
1168        let err = EthApiError::ExecutionTimedOut(Duration::from_secs(10));
1169        assert_eq!(err.to_string(), "execution aborted (timeout = 10s)");
1170    }
1171
1172    #[test]
1173    fn tracing_lookup_errors_use_call_execution_failed_code() {
1174        let cases = [
1175            (EthApiError::TracingTransactionNotFound, "transaction not found"),
1176            (
1177                EthApiError::TracingBlockNotFound(BlockId::hash(B256::with_last_byte(1))),
1178                "block 0x0000000000000000000000000000000000000000000000000000000000000001 not found",
1179            ),
1180            (EthApiError::GenesisNotTraceable, "genesis is not traceable"),
1181        ];
1182
1183        for (error, message) in cases {
1184            let error: jsonrpsee_types::error::ErrorObject<'static> = error.into();
1185            assert_eq!(error.code(), -32000);
1186            assert_eq!(error.message(), message);
1187        }
1188    }
1189
1190    #[test]
1191    fn header_not_found_message() {
1192        let err: jsonrpsee_types::error::ErrorObject<'static> =
1193            EthApiError::HeaderNotFound(BlockId::hash(b256!(
1194                "0x1a15e3c30cf094a99826869517b16d185d45831d3a494f01030b0001a9d3ebb9"
1195            )))
1196            .into();
1197        assert_eq!(
1198            err.message(),
1199            "block not found: hash 0x1a15e3c30cf094a99826869517b16d185d45831d3a494f01030b0001a9d3ebb9"
1200        );
1201        let err: jsonrpsee_types::error::ErrorObject<'static> =
1202            EthApiError::HeaderNotFound(BlockId::hash_canonical(b256!(
1203                "0x1a15e3c30cf094a99826869517b16d185d45831d3a494f01030b0001a9d3ebb9"
1204            )))
1205            .into();
1206        assert_eq!(
1207            err.message(),
1208            "block not found: canonical hash 0x1a15e3c30cf094a99826869517b16d185d45831d3a494f01030b0001a9d3ebb9"
1209        );
1210        let err: jsonrpsee_types::error::ErrorObject<'static> =
1211            EthApiError::HeaderNotFound(BlockId::number(100000)).into();
1212        assert_eq!(err.message(), "block not found: 0x186a0");
1213        let err: jsonrpsee_types::error::ErrorObject<'static> =
1214            EthApiError::HeaderNotFound(BlockId::latest()).into();
1215        assert_eq!(err.message(), "block not found: latest");
1216        let err: jsonrpsee_types::error::ErrorObject<'static> =
1217            EthApiError::HeaderNotFound(BlockId::safe()).into();
1218        assert_eq!(err.message(), "block not found: safe");
1219        let err: jsonrpsee_types::error::ErrorObject<'static> =
1220            EthApiError::HeaderNotFound(BlockId::finalized()).into();
1221        assert_eq!(err.message(), "block not found: finalized");
1222    }
1223
1224    #[test]
1225    fn pruned_history_error_reports_available_range() {
1226        let err: EthApiError =
1227            reth_errors::ProviderError::BlockExpired { requested: 5, earliest_available: 100 }
1228                .into();
1229        assert!(matches!(
1230            err,
1231            EthApiError::PrunedHistoryUnavailable { requested: 5, earliest_available: 100 }
1232        ));
1233
1234        let err: jsonrpsee_types::error::ErrorObject<'static> = err.into();
1235        assert_eq!(err.code(), 4444);
1236        assert_eq!(
1237            err.message(),
1238            "pruned history unavailable: requested 5, earliest available 100"
1239        );
1240    }
1241
1242    #[test]
1243    fn pruned_state_errors_use_history_unavailable_code() {
1244        let err = EthApiError::from(ProviderError::InsufficientChangesets {
1245            requested: 1,
1246            available: 43..=48,
1247        })
1248        .into_rpc_err();
1249        assert_eq!(err.code(), 4444);
1250        assert_eq!(err.message(), "pruned history unavailable: requested 1, earliest available 43");
1251
1252        let err = EthApiError::from(ProviderError::StateAtBlockPruned(7)).into_rpc_err();
1253        assert_eq!(err.code(), 4444);
1254
1255        for requested in [43, 49] {
1256            let err = EthApiError::from(ProviderError::InsufficientChangesets {
1257                requested,
1258                available: 43..=48,
1259            })
1260            .into_rpc_err();
1261            assert_eq!(err.code(), -32603);
1262        }
1263    }
1264
1265    #[test]
1266    fn receipts_not_found_message() {
1267        let err: jsonrpsee_types::error::ErrorObject<'static> =
1268            EthApiError::ReceiptsNotFound(BlockId::hash(b256!(
1269                "0x1a15e3c30cf094a99826869517b16d185d45831d3a494f01030b0001a9d3ebb9"
1270            )))
1271            .into();
1272        assert_eq!(
1273            err.message(),
1274            "block not found: hash 0x1a15e3c30cf094a99826869517b16d185d45831d3a494f01030b0001a9d3ebb9"
1275        );
1276        let err: jsonrpsee_types::error::ErrorObject<'static> =
1277            EthApiError::ReceiptsNotFound(BlockId::hash_canonical(b256!(
1278                "0x1a15e3c30cf094a99826869517b16d185d45831d3a494f01030b0001a9d3ebb9"
1279            )))
1280            .into();
1281        assert_eq!(
1282            err.message(),
1283            "block not found: canonical hash 0x1a15e3c30cf094a99826869517b16d185d45831d3a494f01030b0001a9d3ebb9"
1284        );
1285        let err: jsonrpsee_types::error::ErrorObject<'static> =
1286            EthApiError::ReceiptsNotFound(BlockId::number(100000)).into();
1287        assert_eq!(err.code(), EthRpcErrorCode::ResourceNotFound.code());
1288        assert_eq!(err.message(), "block not found: 0x186a0");
1289        let err: jsonrpsee_types::error::ErrorObject<'static> =
1290            EthApiError::ReceiptsNotFound(BlockId::latest()).into();
1291        assert_eq!(err.message(), "block not found: latest");
1292        let err: jsonrpsee_types::error::ErrorObject<'static> =
1293            EthApiError::ReceiptsNotFound(BlockId::safe()).into();
1294        assert_eq!(err.message(), "block not found: safe");
1295        let err: jsonrpsee_types::error::ErrorObject<'static> =
1296            EthApiError::ReceiptsNotFound(BlockId::finalized()).into();
1297        assert_eq!(err.message(), "block not found: finalized");
1298        let err: jsonrpsee_types::error::ErrorObject<'static> =
1299            EthApiError::ReceiptsNotFound(BlockId::pending()).into();
1300        assert_eq!(err.message(), "block not found: pending");
1301        let err: jsonrpsee_types::error::ErrorObject<'static> =
1302            EthApiError::ReceiptsNotFound(BlockId::earliest()).into();
1303        assert_eq!(err.message(), "block not found: earliest");
1304    }
1305
1306    #[test]
1307    fn revert_err_display() {
1308        let revert = Revert::from("test_revert_reason");
1309        let err = RevertError::new(revert.abi_encode().into());
1310        let msg = err.to_string();
1311        assert_eq!(msg, "execution reverted: test_revert_reason");
1312    }
1313
1314    #[test]
1315    fn empty_revert_err_has_empty_data() {
1316        let err: jsonrpsee_types::error::ErrorObject<'static> =
1317            RpcInvalidTransactionError::Revert(RevertError::new(Bytes::new())).into();
1318        assert_eq!(err.code(), 3);
1319        assert_eq!(err.message(), "execution reverted");
1320        assert_eq!(err.data().unwrap().get(), "\"0x\"");
1321    }
1322}