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,
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 => Self::BlobFeeCapTooLow,
349 InvalidTransaction::BlobVersionedHashesNotSupported => {
350 Self::BlobVersionedHashesNotSupported
351 }
352 InvalidTransaction::MaxFeePerBlobGasNotSupported => Self::MaxFeePerBlobGasNotSupported,
353 InvalidTransaction::BlobCreateTransaction => Self::BlobCreateTransaction,
354 InvalidTransaction::BlobVersionNotSupported => Self::BlobVersionNotSupported,
355 InvalidTransaction::EmptyBlobs => Self::EmptyBlobs,
356 InvalidTransaction::TooManyBlobs { have, max } => Self::TooManyBlobs(have, max),
357 InvalidTransaction::AuthorizationListNotSupported => {
358 Self::AuthorizationListNotSupported
359 }
360 InvalidTransaction::TxGasLimitGreaterThanCap { gas_limit, cap } => {
361 Self::TxGasLimitGreaterThanCap(gas_limit, cap)
362 }
363
364 InvalidTransaction::AuthorizationListInvalidFields
365 | InvalidTransaction::Eip1559NotSupported
366 | InvalidTransaction::Eip2930NotSupported
367 | InvalidTransaction::Eip4844NotSupported
368 | InvalidTransaction::Eip7702NotSupported
369 | InvalidTransaction::EmptyAuthorizationList
370 | InvalidTransaction::Eip7873NotSupported
371 | InvalidTransaction::Eip7873MissingTarget
372 | InvalidTransaction::MissingChainId => Self::Revm(err),
373 }
374 }
375}
376
377impl From<OpTransactionError> for InvalidTransactionError {
378 fn from(value: OpTransactionError) -> Self {
379 match value {
380 OpTransactionError::Base(err) => err.into(),
381 OpTransactionError::DepositSystemTxPostRegolith
382 | OpTransactionError::HaltedDepositPostRegolith => Self::DepositTxErrorPostRegolith,
383 }
384 }
385}
386pub(crate) trait ToRpcResponseResult {
388 fn to_rpc_result(self) -> ResponseResult;
389}
390
391pub fn to_rpc_result<T: Serialize>(val: T) -> ResponseResult {
393 match serde_json::to_value(val) {
394 Ok(success) => ResponseResult::Success(success),
395 Err(err) => {
396 error!(%err, "Failed serialize rpc response");
397 ResponseResult::error(RpcError::internal_error())
398 }
399 }
400}
401
402impl<T: Serialize> ToRpcResponseResult for Result<T> {
403 fn to_rpc_result(self) -> ResponseResult {
404 match self {
405 Ok(val) => to_rpc_result(val),
406 Err(err) => match err {
407 BlockchainError::Pool(err) => {
408 error!(%err, "txpool error");
409 match err {
410 PoolError::CyclicTransaction => {
411 RpcError::transaction_rejected("Cyclic transaction detected")
412 }
413 PoolError::ReplacementUnderpriced(_) => {
414 RpcError::transaction_rejected("replacement transaction underpriced")
415 }
416 PoolError::AlreadyImported(_) => {
417 RpcError::transaction_rejected("transaction already imported")
418 }
419 }
420 }
421 BlockchainError::NoSignerAvailable => {
422 RpcError::invalid_params("No Signer available")
423 }
424 BlockchainError::ChainIdNotAvailable => {
425 RpcError::invalid_params("Chain Id not available")
426 }
427 BlockchainError::TransactionConfirmationTimeout { .. } => {
428 RpcError::internal_error_with("Transaction confirmation timeout")
429 }
430 BlockchainError::InvalidTransaction(err) => match err {
431 InvalidTransactionError::Revert(data) => {
432 let mut msg = "execution reverted".to_string();
434 if let Some(reason) = data
435 .as_ref()
436 .and_then(|data| RevertDecoder::new().maybe_decode(data, None))
437 {
438 msg = format!("{msg}: {reason}");
439 }
440 RpcError {
441 code: ErrorCode::ExecutionError,
443 message: msg.into(),
444 data: serde_json::to_value(data).ok(),
445 }
446 }
447 InvalidTransactionError::GasTooLow => {
448 RpcError {
450 code: ErrorCode::ServerError(-32000),
451 message: err.to_string().into(),
452 data: None,
453 }
454 }
455 InvalidTransactionError::GasTooHigh(_) => {
456 RpcError {
458 code: ErrorCode::ServerError(-32000),
459 message: err.to_string().into(),
460 data: None,
461 }
462 }
463 _ => RpcError::transaction_rejected(err.to_string()),
464 },
465 BlockchainError::FeeHistory(err) => RpcError::invalid_params(err.to_string()),
466 BlockchainError::EmptyRawTransactionData => {
467 RpcError::invalid_params("Empty transaction data")
468 }
469 BlockchainError::FailedToDecodeSignedTransaction => {
470 RpcError::invalid_params("Failed to decode transaction")
471 }
472 BlockchainError::FailedToDecodeTransaction => {
473 RpcError::invalid_params("Failed to decode transaction")
474 }
475 BlockchainError::FailedToDecodeReceipt => {
476 RpcError::invalid_params("Failed to decode receipt")
477 }
478 BlockchainError::FailedToDecodeStateDump => {
479 RpcError::invalid_params("Failed to decode state dump")
480 }
481 BlockchainError::SignerError(err) => RpcError::invalid_params(err.to_string()),
482 BlockchainError::SignatureError(err) => RpcError::invalid_params(err.to_string()),
483 BlockchainError::RpcUnimplemented => {
484 RpcError::internal_error_with("Not implemented")
485 }
486 BlockchainError::PrevrandaoNotSet => RpcError::internal_error_with(err.to_string()),
487 BlockchainError::RpcError(err) => err,
488 BlockchainError::InvalidFeeInput => RpcError::invalid_params(
489 "Invalid input: `max_priority_fee_per_gas` greater than `max_fee_per_gas`",
490 ),
491 BlockchainError::AlloyForkProvider(err) => {
492 error!(target: "backend", %err, "fork provider error");
493 match err {
494 TransportError::ErrorResp(err) => RpcError {
495 code: ErrorCode::from(err.code),
496 message: err.message,
497 data: err.data.and_then(|data| serde_json::to_value(data).ok()),
498 },
499 err => RpcError::internal_error_with(format!("Fork Error: {err:?}")),
500 }
501 }
502 err @ BlockchainError::EvmError(_) => {
503 RpcError::internal_error_with(err.to_string())
504 }
505 err @ BlockchainError::EvmOverrideError(_) => {
506 RpcError::invalid_params(err.to_string())
507 }
508 err @ BlockchainError::InvalidUrl(_) => RpcError::invalid_params(err.to_string()),
509 BlockchainError::Internal(err) => RpcError::internal_error_with(err),
510 err @ BlockchainError::BlockOutOfRange(_, _) => {
511 RpcError::invalid_params(err.to_string())
512 }
513 err @ BlockchainError::BlockNotFound => RpcError {
514 code: ErrorCode::ServerError(-32001),
516 message: err.to_string().into(),
517 data: None,
518 },
519 err @ BlockchainError::TransactionNotFound => RpcError {
520 code: ErrorCode::ServerError(-32001),
521 message: err.to_string().into(),
522 data: None,
523 },
524 err @ BlockchainError::DataUnavailable => {
525 RpcError::internal_error_with(err.to_string())
526 }
527 err @ BlockchainError::TrieError(_) => {
528 RpcError::internal_error_with(err.to_string())
529 }
530 BlockchainError::UintConversion(err) => RpcError::invalid_params(err),
531 err @ BlockchainError::StateOverrideError(_) => {
532 RpcError::invalid_params(err.to_string())
533 }
534 err @ BlockchainError::TimestampError(_) => {
535 RpcError::invalid_params(err.to_string())
536 }
537 BlockchainError::DatabaseError(err) => {
538 RpcError::internal_error_with(err.to_string())
539 }
540 err @ BlockchainError::EIP1559TransactionUnsupportedAtHardfork => {
541 RpcError::invalid_params(err.to_string())
542 }
543 err @ BlockchainError::EIP2930TransactionUnsupportedAtHardfork => {
544 RpcError::invalid_params(err.to_string())
545 }
546 err @ BlockchainError::EIP4844TransactionUnsupportedAtHardfork => {
547 RpcError::invalid_params(err.to_string())
548 }
549 err @ BlockchainError::EIP7702TransactionUnsupportedAtHardfork => {
550 RpcError::invalid_params(err.to_string())
551 }
552 err @ BlockchainError::DepositTransactionUnsupported => {
553 RpcError::invalid_params(err.to_string())
554 }
555 err @ BlockchainError::ExcessBlobGasNotSet => {
556 RpcError::invalid_params(err.to_string())
557 }
558 err @ BlockchainError::Message(_) => RpcError::internal_error_with(err.to_string()),
559 err @ BlockchainError::UnknownTransactionType => {
560 RpcError::invalid_params(err.to_string())
561 }
562 err @ BlockchainError::MissingRequiredFields => {
563 RpcError::invalid_params(err.to_string())
564 }
565 }
566 .into(),
567 }
568 }
569}