Skip to main content

reth_rpc_eth_api/
simulate.rs

1//! Bounded RPC input for `eth_simulateV1`.
2
3use alloy_rpc_types_eth::simulate::{
4    SimulatePayload, SimulatePayloadLimitExceeded, SimulatePayloadSeed,
5};
6use reth_rpc_eth_types::{simulate::EthSimulateError, EthApiError};
7use serde::{
8    de::{DeserializeOwned, DeserializeSeed},
9    Deserialize, Deserializer, Serialize,
10};
11use serde_json::value::RawValue;
12
13/// Maximum number of calls accepted in one `eth_simulateV1` request.
14const MAX_SIMULATE_CALLS: usize = 4096;
15
16/// An `eth_simulateV1` payload that is decoded after the configured block limit is known.
17#[derive(Debug, Serialize)]
18#[serde(untagged)]
19pub enum SimulateV1Request<TxReq> {
20    /// Raw RPC input, retained until the handler can apply its configured limits.
21    Raw(Box<RawValue>),
22    /// A typed payload supplied by an RPC client or internal caller.
23    Parsed(SimulatePayload<TxReq>),
24}
25
26impl<TxReq> From<SimulatePayload<TxReq>> for SimulateV1Request<TxReq> {
27    fn from(payload: SimulatePayload<TxReq>) -> Self {
28        Self::Parsed(payload)
29    }
30}
31
32impl<'de, TxReq> Deserialize<'de> for SimulateV1Request<TxReq> {
33    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
34        Box::<RawValue>::deserialize(deserializer).map(Self::Raw)
35    }
36}
37
38impl<TxReq: DeserializeOwned> SimulateV1Request<TxReq> {
39    /// Decodes RPC input with the configured block limit and the call limit.
40    pub fn into_inner(self, max_blocks: usize) -> Result<SimulatePayload<TxReq>, EthApiError> {
41        let raw = match self {
42            Self::Raw(raw) => raw,
43            Self::Parsed(payload) => return Ok(payload),
44        };
45
46        let mut deserializer = serde_json::Deserializer::from_str(raw.get());
47        let payload = SimulatePayloadSeed::<TxReq>::new(max_blocks, MAX_SIMULATE_CALLS)
48            .deserialize(&mut deserializer)
49            .map_err(|err| EthApiError::InvalidParams(err.to_string()))?;
50        deserializer.end().map_err(|err| EthApiError::InvalidParams(err.to_string()))?;
51        match payload {
52            Ok(payload) => Ok(payload),
53            Err(SimulatePayloadLimitExceeded::Blocks) => {
54                Err(EthApiError::other(EthSimulateError::TooManyBlocks))
55            }
56            Err(err) => Err(EthApiError::InvalidParams(err.to_string())),
57        }
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64    use alloy_rpc_types_eth::{simulate::SimBlock, TransactionRequest};
65    use jsonrpsee_types::error::ErrorObjectOwned;
66
67    fn payload_with_calls(counts: &[usize]) -> String {
68        let blocks = counts
69            .iter()
70            .map(|&count| format!(r#"{{"calls":[{}]}}"#, vec!["{}"; count].join(",")))
71            .collect::<Vec<_>>()
72            .join(",");
73        format!(r#"{{"blockStateCalls":[{blocks}]}}"#)
74    }
75
76    fn parse(
77        input: &str,
78        max_blocks: usize,
79    ) -> Result<SimulatePayload<TransactionRequest>, EthApiError> {
80        serde_json::from_str::<SimulateV1Request<TransactionRequest>>(input)
81            .unwrap()
82            .into_inner(max_blocks)
83    }
84
85    #[test]
86    fn uses_configured_block_limit() {
87        let input = payload_with_calls(&vec![0; 1025]);
88        assert_eq!(parse(&input, 1025).unwrap().block_state_calls.len(), 1025);
89        let err: ErrorObjectOwned = parse(&input, 1024).unwrap_err().into();
90        assert_eq!(err.code(), -38026);
91    }
92
93    #[test]
94    fn bounds_calls_across_blocks() {
95        let input = payload_with_calls(&[MAX_SIMULATE_CALLS - 1, 2]);
96        let err: ErrorObjectOwned = parse(&input, 2).unwrap_err().into();
97        assert_eq!(err.code(), -32602);
98    }
99
100    #[test]
101    fn accepts_call_limit() {
102        let input = payload_with_calls(&[MAX_SIMULATE_CALLS]);
103        assert_eq!(parse(&input, 1).unwrap().block_state_calls[0].calls.len(), MAX_SIMULATE_CALLS);
104    }
105
106    #[test]
107    fn preserves_payload_fields() {
108        let input = r#"{"blockStateCalls":[{"calls":[{}]}],"traceTransfers":true,"validation":true,"returnFullTransactions":true}"#;
109        let expected = serde_json::from_str::<SimulatePayload<TransactionRequest>>(input).unwrap();
110        let parsed = parse(input, 1).unwrap();
111        assert_eq!(serde_json::to_value(parsed).unwrap(), serde_json::to_value(expected).unwrap());
112    }
113
114    #[test]
115    fn serializes_like_alloy_payload() {
116        let payload = SimulatePayload::<TransactionRequest> {
117            block_state_calls: vec![SimBlock::default()],
118            trace_transfers: true,
119            ..Default::default()
120        };
121        let original = serde_json::to_value(&payload).unwrap();
122        let wrapped = serde_json::to_value(SimulateV1Request::from(payload)).unwrap();
123        assert_eq!(wrapped, original);
124    }
125
126    #[test]
127    fn forwards_raw_payload_without_changing_it() {
128        let input = r#"{"blockStateCalls":[{"calls":[{}]}],"validation":true}"#;
129        let wrapped = serde_json::from_str::<SimulateV1Request<TransactionRequest>>(input).unwrap();
130        assert_eq!(serde_json::to_string(&wrapped).unwrap(), input);
131    }
132}