1pub 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
26pub trait ToRpcError: core::error::Error + Send + Sync + 'static {
28 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
51pub type EthResult<T> = Result<T, EthApiError>;
53
54#[derive(Debug, thiserror::Error)]
56pub enum EthApiError {
57 #[error("empty transaction data")]
59 EmptyRawTransactionData,
60 #[error("failed to decode signed transaction")]
62 FailedToDecodeSignedTransaction,
63 #[error("invalid transaction signature")]
65 InvalidTransactionSignature,
66 #[error(transparent)]
68 PoolError(#[from] RpcPoolError),
69 #[error("header not found")]
71 HeaderNotFound(BlockId),
72 #[error("header range not found, start block {0:?}, end block {1:?}")]
74 HeaderRangeNotFound(BlockId, BlockId),
75 #[error("pruned history unavailable: requested {requested}, earliest available {earliest_available}")]
82 PrunedHistoryUnavailable {
83 requested: u64,
85 earliest_available: u64,
87 },
88 #[error("receipts not found")]
90 ReceiptsNotFound(BlockId),
91 #[error("unknown block or tx index")]
93 UnknownBlockOrTxIndex,
94 #[error("invalid block range")]
96 InvalidBlockRange,
97 #[error("request beyond head block: requested {requested}, head {head}")]
99 RequestBeyondHead {
100 requested: u64,
102 head: u64,
104 },
105 #[error("distance to target block exceeds maximum proof window")]
107 ExceedsMaxProofWindow,
108 #[error("prevrandao not in the EVM's environment after merge")]
110 PrevrandaoNotSet,
111 #[error("excess blob gas missing in the EVM's environment after Cancun")]
113 ExcessBlobGasNotSet,
114 #[error("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")]
117 ConflictingFeeFieldsInRequest,
118 #[error(transparent)]
120 InvalidTransaction(#[from] RpcInvalidTransactionError),
121 #[error(transparent)]
123 InvalidBlockData(#[from] BlockError),
124 #[error("account {0:?} has both 'state' and 'stateDiff'")]
126 BothStateAndStateDiffInOverride(Address),
127 #[error(transparent)]
129 Internal(RethError),
130 #[error(transparent)]
132 Signing(#[from] SignError),
133 #[error("transaction not found")]
135 TransactionNotFound,
136 #[error("transaction not found")]
138 TracingTransactionNotFound,
139 #[error("block not found")]
141 TracingBlockNotFound(BlockId),
142 #[error("genesis is not traceable")]
144 GenesisNotTraceable,
145 #[error("unsupported")]
147 Unsupported(&'static str),
148 #[error("{0}")]
150 InvalidParams(String),
151 #[error("invalid tracer config")]
153 InvalidTracerConfig,
154 #[error("invalid reward percentiles")]
156 InvalidRewardPercentiles,
157 #[error("internal blocking task error")]
162 InternalBlockingTaskError,
163 #[error("internal eth error")]
165 InternalEthError,
166 #[error("execution aborted (timeout = {0:?})")]
168 ExecutionTimedOut(Duration),
169 #[error("{0}")]
171 InternalJsTracerError(String),
172 #[error(transparent)]
173 TransactionInputError(#[from] TransactionInputError),
175 #[error("EVM error: {0}")]
177 EvmCustom(String),
178 #[error("Invalid bytecode: {0}")]
184 InvalidBytecode(String),
185 #[error(transparent)]
187 TransactionConversionError(#[from] TransactionConversionError),
188 #[error("{0}")]
190 MuxTracerError(String),
191 #[error(
193 "Transaction {hash} was added to the mempool but wasn't confirmed within {duration:?}."
194 )]
195 TransactionConfirmationTimeout {
196 hash: B256,
198 duration: Duration,
200 },
201 #[error(transparent)]
203 BatchTxRecvError(#[from] RecvError),
204 #[error("Batch transaction sender channel closed")]
206 BatchTxSendError,
207 #[error("call_many error in bundle {bundle_index} and transaction {tx_index}: {}", .error.message())]
209 CallManyError {
210 bundle_index: usize,
212 tx_index: usize,
214 error: jsonrpsee_types::ErrorObject<'static>,
216 },
217 #[error("Block access list not available for pre-Amsterdam blocks")]
219 BlockAccessListNotAvailablePreAmsterdam,
220 #[error("the request's calls exceed the RPC gas cap of {0}")]
223 CallManyGasCapExceeded(u64),
224 #[error("{0}")]
226 Other(Box<dyn ToRpcError>),
227}
228
229#[derive(Debug, thiserror::Error)]
231#[error("insufficient funds: cost {cost} > balance {balance}")]
232pub struct InsufficientFundsError {
233 pub cost: U256,
235 pub balance: U256,
237}
238
239#[derive(Debug, thiserror::Error)]
241pub enum CallError<E> {
242 #[error(transparent)]
244 Database(E),
245 #[error(transparent)]
247 InsufficientFunds(#[from] InsufficientFundsError),
248}
249
250#[derive(Debug, thiserror::Error)]
252pub enum StateOverrideError<E> {
253 #[error(transparent)]
255 InvalidBytecode(#[from] evm2::bytecode::BytecodeDecodeError),
256 #[error("Both 'state' and 'stateDiff' fields are set for account {0}")]
258 BothStateAndStateDiff(Address),
259 #[error(transparent)]
261 Database(E),
262}
263
264impl EthApiError {
265 pub fn other<E: ToRpcError>(err: E) -> Self {
267 Self::Other(Box::new(err))
268 }
269
270 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 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 pub const fn is_gas_too_low(&self) -> bool {
292 matches!(self, Self::InvalidTransaction(RpcInvalidTransactionError::GasTooLow))
293 }
294
295 pub const fn as_invalid_transaction(&self) -> Option<&RpcInvalidTransactionError> {
297 match self {
298 Self::InvalidTransaction(e) => Some(e),
299 _ => None,
300 }
301 }
302
303 pub fn from_state_overrides_err<E>(err: StateOverrideError<E>) -> Self
305 where
306 E: Into<Self>,
307 {
308 err.into()
309 }
310
311 pub fn from_call_err<E>(err: CallError<E>) -> Self
313 where
314 E: Into<Self>,
315 {
316 err.into()
317 }
318
319 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#[derive(thiserror::Error, Debug)]
648pub enum RpcInvalidTransactionError {
649 #[error("nonce too low: next nonce {state}, tx nonce {tx}")]
651 NonceTooLow {
652 tx: u64,
654 state: u64,
656 },
657 #[error("nonce too high")]
660 NonceTooHigh,
661 #[error("nonce has max value")]
664 NonceMaxValue,
665 #[error("insufficient funds for transfer")]
667 InsufficientFundsForTransfer,
668 #[error("max initcode size exceeded")]
670 MaxInitCodeSizeExceeded,
671 #[error("insufficient funds for gas * price + value: have {balance} want {cost}")]
673 InsufficientFunds {
674 cost: U256,
676 balance: U256,
678 },
679 #[error("gas required exceeds allowance ({gas_limit})")]
685 GasRequiredExceedsAllowance {
686 gas_limit: u64,
688 },
689 #[error("gas uint64 overflow")]
691 GasUintOverflow,
692 #[error("intrinsic gas too low")]
695 GasTooLow,
696 #[error("intrinsic gas too high")]
698 GasTooHigh,
699 #[error("gas limit too high")]
701 GasLimitTooHigh,
702 #[error("transaction type not supported")]
704 TxTypeNotSupported,
705 #[error("max priority fee per gas higher than max fee per gas")]
708 TipAboveFeeCap,
709 #[error("max priority fee per gas higher than 2^256-1")]
711 TipVeryHigh,
712 #[error("max fee per gas higher than 2^256-1")]
714 FeeCapVeryHigh,
715 #[error("max fee per gas less than block base fee")]
717 FeeCapTooLow,
718 #[error("sender is not an EOA")]
720 SenderNoEOA,
721 #[error("out of gas: gas required exceeds: {0}")]
724 BasicOutOfGas(u64),
725 #[error("out of gas: gas exhausted during memory expansion: {0}")]
728 MemoryOutOfGas(u64),
729 #[error("out of memory: memory limit exceeded during memory expansion")]
731 MemoryLimitOutOfGas,
732 #[error("out of gas: gas exhausted during precompiled contract execution: {0}")]
735 PrecompileOutOfGas(u64),
736 #[error("out of gas: invalid operand to an opcode: {0}")]
739 InvalidOperandOutOfGas(u64),
740 #[error(transparent)]
742 Revert(RevertError),
743 #[error("EVM error: {0}")]
745 EvmHalt(String),
746 #[error("invalid chain ID")]
748 InvalidChainId,
749 #[error("transactions before Spurious Dragon should not have a chain ID")]
751 OldLegacyChainId,
752 #[error("transactions before Berlin should not have access list")]
754 AccessListNotSupported,
755 #[error("max_fee_per_blob_gas is not supported for blocks before the Cancun hardfork")]
757 MaxFeePerBlobGasNotSupported,
758 #[error("blob_versioned_hashes is not supported for blocks before the Cancun hardfork")]
761 BlobVersionedHashesNotSupported,
762 #[error("max fee per blob gas less than block blob gas fee")]
764 BlobFeeCapTooLow,
765 #[error("blob hash version mismatch")]
767 BlobHashVersionMismatch,
768 #[error("blob transaction missing blob hashes")]
770 BlobTransactionMissingBlobHashes,
771 #[error("blob transaction exceeds max blobs per block; got {have}")]
773 TooManyBlobs {
774 have: usize,
776 },
777 #[error("blob transaction is a create transaction")]
779 BlobTransactionIsCreate,
780 #[error("EIP-7702 authorization list not supported")]
782 AuthorizationListNotSupported,
783 #[error("EIP-7702 authorization list has invalid fields")]
785 AuthorizationListInvalidFields,
786 #[error("transaction priority fee below minimum required priority fee {minimum_priority_fee}")]
788 PriorityFeeBelowMinimum {
789 minimum_priority_fee: u128,
791 },
792 #[error("{0}")]
794 Other(Box<dyn ToRpcError>),
795}
796
797impl RpcInvalidTransactionError {
798 pub fn other<E: ToRpcError>(err: E) -> Self {
800 Self::Other(Box::new(err))
801 }
802
803 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 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 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 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 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#[derive(Debug, Clone, thiserror::Error)]
925pub struct RevertError {
926 output: Bytes,
928}
929
930impl RevertError {
933 pub const fn new(output: Bytes) -> Self {
937 Self { output }
938 }
939
940 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 error = error.trim_start_matches("revert: ");
957 }
958 write!(f, ": {error}")?;
959 }
960 Ok(())
961 }
962}
963
964#[derive(Debug, thiserror::Error)]
966pub enum RpcPoolError {
967 #[error("already known")]
969 AlreadyKnown,
970 #[error("invalid sender")]
972 InvalidSender,
973 #[error("transaction underpriced")]
975 Underpriced,
976 #[error("txpool is full")]
978 TxPoolOverflow,
979 #[error("replacement transaction underpriced")]
981 ReplaceUnderpriced,
982 #[error("exceeds block gas limit")]
984 ExceedsGasLimit,
985 #[error("exceeds max transaction gas limit")]
987 MaxTxGasLimitExceeded,
988 #[error("tx fee ({max_tx_fee_wei} wei) exceeds the configured cap ({tx_fee_cap_wei} wei)")]
991 ExceedsFeeCap {
992 max_tx_fee_wei: u128,
994 tx_fee_cap_wei: u128,
996 },
997 #[error("negative value")]
999 NegativeValue,
1000 #[error("oversized data: transaction size {size}, limit {limit}")]
1002 OversizedData {
1003 size: usize,
1005 limit: usize,
1007 },
1008 #[error("max initcode size exceeded")]
1010 ExceedsMaxInitCodeSize,
1011 #[error(transparent)]
1013 Invalid(#[from] RpcInvalidTransactionError),
1014 #[error(transparent)]
1016 PoolTransactionError(Box<dyn PoolTransactionError>),
1017 #[error(transparent)]
1019 Eip4844(#[from] Eip4844PoolTransactionError),
1020 #[error(transparent)]
1022 Eip7702(#[from] Eip7702PoolTransactionError),
1023 #[error("address already reserved")]
1028 AddressAlreadyReserved,
1029 #[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#[derive(Debug, thiserror::Error)]
1123pub enum SignError {
1124 #[error("could not sign")]
1126 CouldNotSign,
1127 #[error("unknown account")]
1129 NoAccount,
1130 #[error("given typed data is not valid")]
1132 InvalidTypedData,
1133 #[error("invalid transaction request")]
1135 InvalidTransactionRequest,
1136 #[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}