1use crate::eth::pool::transactions::PoolTransaction;
4use alloy_evm::overrides::StateOverrideError;
5use alloy_primitives::{B256, Bytes, SignatureError};
6use alloy_rpc_types::BlockNumberOrTag;
7use alloy_signer::Error as SignerError;
8use alloy_transport::TransportError;
9use anvil_core::eth::wallet::WalletError;
10use anvil_rpc::{
11 error::{ErrorCode, RpcError},
12 response::ResponseResult,
13};
14use foundry_evm::{backend::DatabaseError, decode::RevertDecoder};
15use op_revm::OpTransactionError;
16use revm::{
17 context_interface::result::{EVMError, InvalidHeader, InvalidTransaction},
18 interpreter::InstructionResult,
19};
20use serde::Serialize;
21use tokio::time::Duration;
22
23pub(crate) type Result<T> = std::result::Result<T, BlockchainError>;
24
25#[derive(Debug, thiserror::Error)]
26pub enum BlockchainError {
27 #[error(transparent)]
28 Pool(#[from] PoolError),
29 #[error("No signer available")]
30 NoSignerAvailable,
31 #[error("Chain Id not available")]
32 ChainIdNotAvailable,
33 #[error("Invalid input: `max_priority_fee_per_gas` greater than `max_fee_per_gas`")]
34 InvalidFeeInput,
35 #[error("Transaction data is empty")]
36 EmptyRawTransactionData,
37 #[error("Failed to decode signed transaction")]
38 FailedToDecodeSignedTransaction,
39 #[error("Failed to decode transaction")]
40 FailedToDecodeTransaction,
41 #[error("Failed to decode receipt")]
42 FailedToDecodeReceipt,
43 #[error("Failed to decode state")]
44 FailedToDecodeStateDump,
45 #[error("Prevrandao not in the EVM's environment after merge")]
46 PrevrandaoNotSet,
47 #[error(transparent)]
48 SignatureError(#[from] SignatureError),
49 #[error(transparent)]
50 SignerError(#[from] SignerError),
51 #[error("Rpc Endpoint not implemented")]
52 RpcUnimplemented,
53 #[error("Rpc error {0:?}")]
54 RpcError(RpcError),
55 #[error(transparent)]
56 InvalidTransaction(#[from] InvalidTransactionError),
57 #[error(transparent)]
58 FeeHistory(#[from] FeeHistoryError),
59 #[error(transparent)]
60 AlloyForkProvider(#[from] TransportError),
61 #[error("EVM error {0:?}")]
62 EvmError(InstructionResult),
63 #[error("Evm override error: {0}")]
64 EvmOverrideError(String),
65 #[error("Invalid url {0:?}")]
66 InvalidUrl(String),
67 #[error("Internal error: {0:?}")]
68 Internal(String),
69 #[error("BlockOutOfRangeError: block height is {0} but requested was {1}")]
70 BlockOutOfRange(u64, u64),
71 #[error("Resource not found")]
72 BlockNotFound,
73 #[error("transaction not found")]
75 TransactionNotFound,
76 #[error("Required data unavailable")]
77 DataUnavailable,
78 #[error("Trie error: {0}")]
79 TrieError(String),
80 #[error("{0}")]
81 UintConversion(&'static str),
82 #[error("State override error: {0}")]
83 StateOverrideError(String),
84 #[error("Timestamp error: {0}")]
85 TimestampError(String),
86 #[error(transparent)]
87 DatabaseError(#[from] DatabaseError),
88 #[error(
89 "EIP-1559 style fee params (maxFeePerGas or maxPriorityFeePerGas) received but they are not supported by the current hardfork.\n\nYou can use them by running anvil with '--hardfork london' or later."
90 )]
91 EIP1559TransactionUnsupportedAtHardfork,
92 #[error(
93 "Access list received but is not supported by the current hardfork.\n\nYou can use it by running anvil with '--hardfork berlin' or later."
94 )]
95 EIP2930TransactionUnsupportedAtHardfork,
96 #[error(
97 "EIP-4844 fields received but is not supported by the current hardfork.\n\nYou can use it by running anvil with '--hardfork cancun' or later."
98 )]
99 EIP4844TransactionUnsupportedAtHardfork,
100 #[error(
101 "EIP-7702 fields received but is not supported by the current hardfork.\n\nYou can use it by running anvil with '--hardfork prague' or later."
102 )]
103 EIP7702TransactionUnsupportedAtHardfork,
104 #[error(
105 "op-stack deposit tx received but is not supported.\n\nYou can use it by running anvil with '--optimism'."
106 )]
107 DepositTransactionUnsupported,
108 #[error("Unknown transaction type not supported")]
109 UnknownTransactionType,
110 #[error("Excess blob gas not set.")]
111 ExcessBlobGasNotSet,
112 #[error("{0}")]
113 Message(String),
114 #[error("Transaction {hash} was added to the mempool but wasn't confirmed within {duration:?}")]
115 TransactionConfirmationTimeout {
116 hash: B256,
118 duration: Duration,
120 },
121 #[error("Failed to parse transaction request: missing required fields")]
122 MissingRequiredFields,
123}
124
125impl From<eyre::Report> for BlockchainError {
126 fn from(err: eyre::Report) -> Self {
127 Self::Message(err.to_string())
128 }
129}
130
131impl From<RpcError> for BlockchainError {
132 fn from(err: RpcError) -> Self {
133 Self::RpcError(err)
134 }
135}
136
137impl<T> From<EVMError<T>> for BlockchainError
138where
139 T: Into<Self>,
140{
141 fn from(err: EVMError<T>) -> Self {
142 match err {
143 EVMError::Transaction(err) => InvalidTransactionError::from(err).into(),
144 EVMError::Header(err) => match err {
145 InvalidHeader::ExcessBlobGasNotSet => Self::ExcessBlobGasNotSet,
146 InvalidHeader::PrevrandaoNotSet => Self::PrevrandaoNotSet,
147 },
148 EVMError::Database(err) => err.into(),
149 EVMError::Custom(err) => Self::Message(err),
150 }
151 }
152}
153
154impl<T> From<EVMError<T, OpTransactionError>> for BlockchainError
155where
156 T: Into<Self>,
157{
158 fn from(err: EVMError<T, OpTransactionError>) -> Self {
159 match err {
160 EVMError::Transaction(err) => match err {
161 OpTransactionError::Base(err) => InvalidTransactionError::from(err).into(),
162 OpTransactionError::DepositSystemTxPostRegolith => {
163 Self::DepositTransactionUnsupported
164 }
165 OpTransactionError::HaltedDepositPostRegolith => {
166 Self::DepositTransactionUnsupported
167 }
168 },
169 EVMError::Header(err) => match err {
170 InvalidHeader::ExcessBlobGasNotSet => Self::ExcessBlobGasNotSet,
171 InvalidHeader::PrevrandaoNotSet => Self::PrevrandaoNotSet,
172 },
173 EVMError::Database(err) => err.into(),
174 EVMError::Custom(err) => Self::Message(err),
175 }
176 }
177}
178
179impl From<WalletError> for BlockchainError {
180 fn from(value: WalletError) -> Self {
181 Self::Message(value.to_string())
182 }
183}
184
185impl<E> From<StateOverrideError<E>> for BlockchainError
186where
187 E: Into<Self>,
188{
189 fn from(value: StateOverrideError<E>) -> Self {
190 match value {
191 StateOverrideError::InvalidBytecode(err) => Self::StateOverrideError(err.to_string()),
192 StateOverrideError::BothStateAndStateDiff(addr) => Self::StateOverrideError(format!(
193 "state and state_diff can't be used together for account {addr}",
194 )),
195 StateOverrideError::Database(err) => err.into(),
196 }
197 }
198}
199
200#[derive(Debug, thiserror::Error)]
202pub enum PoolError {
203 #[error("Transaction with cyclic dependent transactions")]
204 CyclicTransaction,
205 #[error("Tx: [{0:?}] insufficient gas price to replace existing transaction")]
207 ReplacementUnderpriced(Box<PoolTransaction>),
208 #[error("Tx: [{0:?}] already Imported")]
209 AlreadyImported(Box<PoolTransaction>),
210}
211
212#[derive(Debug, thiserror::Error)]
214pub enum FeeHistoryError {
215 #[error("requested block range is out of bounds")]
216 InvalidBlockRange,
217 #[error("could not find newest block number requested: {0}")]
218 BlockNotFound(BlockNumberOrTag),
219}
220
221#[derive(Debug)]
222pub struct ErrDetail {
223 pub detail: String,
224}
225
226#[derive(Debug, thiserror::Error)]
228pub enum InvalidTransactionError {
229 #[error("nonce too low")]
231 NonceTooLow,
232 #[error("Nonce too high")]
235 NonceTooHigh,
236 #[error("nonce has max value")]
239 NonceMaxValue,
240 #[error("insufficient funds for transfer")]
242 InsufficientFundsForTransfer,
243 #[error("max initcode size exceeded")]
245 MaxInitCodeSizeExceeded,
246 #[error("Insufficient funds for gas * price + value")]
248 InsufficientFunds,
249 #[error("gas uint64 overflow")]
251 GasUintOverflow,
252 #[error("intrinsic gas too low")]
255 GasTooLow,
256 #[error("intrinsic gas too high -- {}",.0.detail)]
258 GasTooHigh(ErrDetail),
259 #[error("max priority fee per gas higher than max fee per gas")]
262 TipAboveFeeCap,
263 #[error("max fee per gas less than block base fee")]
265 FeeCapTooLow,
266 #[error("Out of gas: gas required exceeds allowance: {0:?}")]
268 BasicOutOfGas(u128),
269 #[error("execution reverted: {0:?}")]
271 Revert(Option<Bytes>),
272 #[error("sender not an eoa")]
274 SenderNoEOA,
275 #[error("invalid chain id for signer")]
277 InvalidChainId,
278 #[error("Incompatible EIP-155 transaction, signed for another chain")]
280 IncompatibleEIP155,
281 #[error("Access lists are not supported before the Berlin hardfork")]
283 AccessListNotSupported,
284 #[error("Block `blob_gas_price` is greater than tx-specified `max_fee_per_blob_gas`")]
287 BlobFeeCapTooLow(u128, u128),
288 #[error("Block `blob_versioned_hashes` is not supported before the Cancun hardfork")]
291 BlobVersionedHashesNotSupported,
292 #[error("`max_fee_per_blob_gas` is not supported for blocks before the Cancun hardfork.")]
294 MaxFeePerBlobGasNotSupported,
295 #[error("`blob_hashes` are required for EIP-4844 transactions")]
297 NoBlobHashes,
298 #[error("too many blobs in one transaction, have: {0}, max: {1}")]
299 TooManyBlobs(usize, usize),
300 #[error(transparent)]
302 BlobTransactionValidationError(#[from] alloy_consensus::BlobTransactionValidationError),
303 #[error("Blob transaction can't be a create transaction. `to` must be present.")]
305 BlobCreateTransaction,
306 #[error("Blob transaction contains a versioned hash with an incorrect version")]
308 BlobVersionNotSupported,
309 #[error("There should be at least one blob in a Blob transaction.")]
311 EmptyBlobs,
312 #[error("EIP-7702 authorization lists are not supported before the Prague hardfork")]
314 AuthorizationListNotSupported,
315 #[error("Transaction gas limit is greater than the block gas limit, gas_limit: {0}, cap: {1}")]
316 TxGasLimitGreaterThanCap(u64, u64),
317 #[error(transparent)]
319 Revm(revm::context_interface::result::InvalidTransaction),
320 #[error("op-deposit failure post regolith")]
322 DepositTxErrorPostRegolith,
323}
324
325impl From<InvalidTransaction> for InvalidTransactionError {
326 fn from(err: InvalidTransaction) -> Self {
327 match err {
328 InvalidTransaction::InvalidChainId => Self::InvalidChainId,
329 InvalidTransaction::PriorityFeeGreaterThanMaxFee => Self::TipAboveFeeCap,
330 InvalidTransaction::GasPriceLessThanBasefee => Self::FeeCapTooLow,
331 InvalidTransaction::CallerGasLimitMoreThanBlock => {
332 Self::GasTooHigh(ErrDetail { detail: String::from("CallerGasLimitMoreThanBlock") })
333 }
334 InvalidTransaction::CallGasCostMoreThanGasLimit { .. } => {
335 Self::GasTooHigh(ErrDetail { detail: String::from("CallGasCostMoreThanGasLimit") })
336 }
337 InvalidTransaction::GasFloorMoreThanGasLimit { .. } => {
338 Self::GasTooHigh(ErrDetail { detail: String::from("GasFloorMoreThanGasLimit") })
339 }
340 InvalidTransaction::RejectCallerWithCode => Self::SenderNoEOA,
341 InvalidTransaction::LackOfFundForMaxFee { .. } => Self::InsufficientFunds,
342 InvalidTransaction::OverflowPaymentInTransaction => Self::GasUintOverflow,
343 InvalidTransaction::NonceOverflowInTransaction => Self::NonceMaxValue,
344 InvalidTransaction::CreateInitCodeSizeLimit => Self::MaxInitCodeSizeExceeded,
345 InvalidTransaction::NonceTooHigh { .. } => Self::NonceTooHigh,
346 InvalidTransaction::NonceTooLow { .. } => Self::NonceTooLow,
347 InvalidTransaction::AccessListNotSupported => Self::AccessListNotSupported,
348 InvalidTransaction::BlobGasPriceGreaterThanMax {
349 block_blob_gas_price,
350 tx_max_fee_per_blob_gas,
351 } => Self::BlobFeeCapTooLow(block_blob_gas_price, tx_max_fee_per_blob_gas),
352 InvalidTransaction::BlobVersionedHashesNotSupported => {
353 Self::BlobVersionedHashesNotSupported
354 }
355 InvalidTransaction::MaxFeePerBlobGasNotSupported => Self::MaxFeePerBlobGasNotSupported,
356 InvalidTransaction::BlobCreateTransaction => Self::BlobCreateTransaction,
357 InvalidTransaction::BlobVersionNotSupported => Self::BlobVersionNotSupported,
358 InvalidTransaction::EmptyBlobs => Self::EmptyBlobs,
359 InvalidTransaction::TooManyBlobs { have, max } => Self::TooManyBlobs(have, max),
360 InvalidTransaction::AuthorizationListNotSupported => {
361 Self::AuthorizationListNotSupported
362 }
363 InvalidTransaction::TxGasLimitGreaterThanCap { gas_limit, cap } => {
364 Self::TxGasLimitGreaterThanCap(gas_limit, cap)
365 }
366
367 InvalidTransaction::AuthorizationListInvalidFields
368 | InvalidTransaction::Eip1559NotSupported
369 | InvalidTransaction::Eip2930NotSupported
370 | InvalidTransaction::Eip4844NotSupported
371 | InvalidTransaction::Eip7702NotSupported
372 | InvalidTransaction::EmptyAuthorizationList
373 | InvalidTransaction::Eip7873NotSupported
374 | InvalidTransaction::Eip7873MissingTarget
375 | InvalidTransaction::MissingChainId
376 | InvalidTransaction::Str(_) => Self::Revm(err),
377 }
378 }
379}
380
381impl From<OpTransactionError> for InvalidTransactionError {
382 fn from(value: OpTransactionError) -> Self {
383 match value {
384 OpTransactionError::Base(err) => err.into(),
385 OpTransactionError::DepositSystemTxPostRegolith
386 | OpTransactionError::HaltedDepositPostRegolith => Self::DepositTxErrorPostRegolith,
387 }
388 }
389}
390pub(crate) trait ToRpcResponseResult {
392 fn to_rpc_result(self) -> ResponseResult;
393}
394
395pub fn to_rpc_result<T: Serialize>(val: T) -> ResponseResult {
397 match serde_json::to_value(val) {
398 Ok(success) => ResponseResult::Success(success),
399 Err(err) => {
400 error!(%err, "Failed serialize rpc response");
401 ResponseResult::error(RpcError::internal_error())
402 }
403 }
404}
405
406impl<T: Serialize> ToRpcResponseResult for Result<T> {
407 fn to_rpc_result(self) -> ResponseResult {
408 match self {
409 Ok(val) => to_rpc_result(val),
410 Err(err) => match err {
411 BlockchainError::Pool(err) => {
412 error!(%err, "txpool error");
413 match err {
414 PoolError::CyclicTransaction => {
415 RpcError::transaction_rejected("Cyclic transaction detected")
416 }
417 PoolError::ReplacementUnderpriced(_) => {
418 RpcError::transaction_rejected("replacement transaction underpriced")
419 }
420 PoolError::AlreadyImported(_) => {
421 RpcError::transaction_rejected("transaction already imported")
422 }
423 }
424 }
425 BlockchainError::NoSignerAvailable => {
426 RpcError::invalid_params("No Signer available")
427 }
428 BlockchainError::ChainIdNotAvailable => {
429 RpcError::invalid_params("Chain Id not available")
430 }
431 BlockchainError::TransactionConfirmationTimeout { .. } => {
432 RpcError::internal_error_with("Transaction confirmation timeout")
433 }
434 BlockchainError::InvalidTransaction(err) => match err {
435 InvalidTransactionError::Revert(data) => {
436 let mut msg = "execution reverted".to_string();
438 if let Some(reason) = data
439 .as_ref()
440 .and_then(|data| RevertDecoder::new().maybe_decode(data, None))
441 {
442 msg = format!("{msg}: {reason}");
443 }
444 RpcError {
445 code: ErrorCode::ExecutionError,
447 message: msg.into(),
448 data: serde_json::to_value(data).ok(),
449 }
450 }
451 InvalidTransactionError::GasTooLow => {
452 RpcError {
454 code: ErrorCode::ServerError(-32000),
455 message: err.to_string().into(),
456 data: None,
457 }
458 }
459 InvalidTransactionError::GasTooHigh(_) => {
460 RpcError {
462 code: ErrorCode::ServerError(-32000),
463 message: err.to_string().into(),
464 data: None,
465 }
466 }
467 _ => RpcError::transaction_rejected(err.to_string()),
468 },
469 BlockchainError::FeeHistory(err) => RpcError::invalid_params(err.to_string()),
470 BlockchainError::EmptyRawTransactionData => {
471 RpcError::invalid_params("Empty transaction data")
472 }
473 BlockchainError::FailedToDecodeSignedTransaction => {
474 RpcError::invalid_params("Failed to decode transaction")
475 }
476 BlockchainError::FailedToDecodeTransaction => {
477 RpcError::invalid_params("Failed to decode transaction")
478 }
479 BlockchainError::FailedToDecodeReceipt => {
480 RpcError::invalid_params("Failed to decode receipt")
481 }
482 BlockchainError::FailedToDecodeStateDump => {
483 RpcError::invalid_params("Failed to decode state dump")
484 }
485 BlockchainError::SignerError(err) => RpcError::invalid_params(err.to_string()),
486 BlockchainError::SignatureError(err) => RpcError::invalid_params(err.to_string()),
487 BlockchainError::RpcUnimplemented => {
488 RpcError::internal_error_with("Not implemented")
489 }
490 BlockchainError::PrevrandaoNotSet => RpcError::internal_error_with(err.to_string()),
491 BlockchainError::RpcError(err) => err,
492 BlockchainError::InvalidFeeInput => RpcError::invalid_params(
493 "Invalid input: `max_priority_fee_per_gas` greater than `max_fee_per_gas`",
494 ),
495 BlockchainError::AlloyForkProvider(err) => {
496 error!(target: "backend", %err, "fork provider error");
497 match err {
498 TransportError::ErrorResp(err) => RpcError {
499 code: ErrorCode::from(err.code),
500 message: err.message,
501 data: err.data.and_then(|data| serde_json::to_value(data).ok()),
502 },
503 err => RpcError::internal_error_with(format!("Fork Error: {err:?}")),
504 }
505 }
506 err @ BlockchainError::EvmError(_) => {
507 RpcError::internal_error_with(err.to_string())
508 }
509 err @ BlockchainError::EvmOverrideError(_) => {
510 RpcError::invalid_params(err.to_string())
511 }
512 err @ BlockchainError::InvalidUrl(_) => RpcError::invalid_params(err.to_string()),
513 BlockchainError::Internal(err) => RpcError::internal_error_with(err),
514 err @ BlockchainError::BlockOutOfRange(_, _) => {
515 RpcError::invalid_params(err.to_string())
516 }
517 err @ BlockchainError::BlockNotFound => RpcError {
518 code: ErrorCode::ServerError(-32001),
520 message: err.to_string().into(),
521 data: None,
522 },
523 err @ BlockchainError::TransactionNotFound => RpcError {
524 code: ErrorCode::ServerError(-32001),
525 message: err.to_string().into(),
526 data: None,
527 },
528 err @ BlockchainError::DataUnavailable => {
529 RpcError::internal_error_with(err.to_string())
530 }
531 err @ BlockchainError::TrieError(_) => {
532 RpcError::internal_error_with(err.to_string())
533 }
534 BlockchainError::UintConversion(err) => RpcError::invalid_params(err),
535 err @ BlockchainError::StateOverrideError(_) => {
536 RpcError::invalid_params(err.to_string())
537 }
538 err @ BlockchainError::TimestampError(_) => {
539 RpcError::invalid_params(err.to_string())
540 }
541 BlockchainError::DatabaseError(err) => {
542 RpcError::internal_error_with(err.to_string())
543 }
544 err @ BlockchainError::EIP1559TransactionUnsupportedAtHardfork => {
545 RpcError::invalid_params(err.to_string())
546 }
547 err @ BlockchainError::EIP2930TransactionUnsupportedAtHardfork => {
548 RpcError::invalid_params(err.to_string())
549 }
550 err @ BlockchainError::EIP4844TransactionUnsupportedAtHardfork => {
551 RpcError::invalid_params(err.to_string())
552 }
553 err @ BlockchainError::EIP7702TransactionUnsupportedAtHardfork => {
554 RpcError::invalid_params(err.to_string())
555 }
556 err @ BlockchainError::DepositTransactionUnsupported => {
557 RpcError::invalid_params(err.to_string())
558 }
559 err @ BlockchainError::ExcessBlobGasNotSet => {
560 RpcError::invalid_params(err.to_string())
561 }
562 err @ BlockchainError::Message(_) => RpcError::internal_error_with(err.to_string()),
563 err @ BlockchainError::UnknownTransactionType => {
564 RpcError::invalid_params(err.to_string())
565 }
566 err @ BlockchainError::MissingRequiredFields => {
567 RpcError::invalid_params(err.to_string())
568 }
569 }
570 .into(),
571 }
572 }
573}