Skip to main content

alloy_rpc_types_mev/
stats.rs

1use crate::{u256_numeric_string, ConsideredByBuildersAt, SealedByBuildersAt};
2
3use alloy_primitives::U256;
4use serde::{Deserialize, Deserializer, Serialize, Serializer};
5
6/// Response for `flashbots_getBundleStatsV2` represents stats for a single bundle
7///
8/// Note: this is V2: <https://docs.flashbots.net/flashbots-auction/searchers/advanced/rpc-endpoint#flashbots_getbundlestatsv2>
9///
10/// Timestamp format: "2022-10-06T21:36:06.322Z"
11#[derive(Default, Debug, Clone, PartialEq, Eq)]
12pub enum BundleStats {
13    /// The relayer has not yet seen the bundle.
14    #[default]
15    Unknown,
16    /// The relayer has seen the bundle, but has not simulated it yet.
17    Seen(StatsSeen),
18    /// The relayer has seen the bundle and has simulated it.
19    Simulated(StatsSimulated),
20}
21
22impl Serialize for BundleStats {
23    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
24        match self {
25            Self::Unknown => serde_json::json!({"isSimulated": false}).serialize(serializer),
26            Self::Seen(stats) => stats.serialize(serializer),
27            Self::Simulated(stats) => stats.serialize(serializer),
28        }
29    }
30}
31
32impl<'de> Deserialize<'de> for BundleStats {
33    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
34    where
35        D: Deserializer<'de>,
36    {
37        let map = serde_json::Map::deserialize(deserializer)?;
38
39        if map.get("receivedAt").is_none() {
40            Ok(Self::Unknown)
41        } else if map.get("isSimulated").is_some_and(|v| *v == false) {
42            StatsSeen::deserialize(serde_json::Value::Object(map))
43                .map(BundleStats::Seen)
44                .map_err(serde::de::Error::custom)
45        } else {
46            StatsSimulated::deserialize(serde_json::Value::Object(map))
47                .map(BundleStats::Simulated)
48                .map_err(serde::de::Error::custom)
49        }
50    }
51}
52
53/// Response for `flashbots_getBundleStatsV2` represents stats for a single bundle
54///
55/// Note: this is V2: <https://docs.flashbots.net/flashbots-auction/searchers/advanced/rpc-endpoint#flashbots_getbundlestatsv2>
56///
57/// Timestamp format: "2022-10-06T21:36:06.322Z
58#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(rename_all = "camelCase")]
60pub struct StatsSeen {
61    /// boolean representing if this searcher has a high enough reputation to be in the high
62    /// priority queue
63    pub is_high_priority: bool,
64    /// representing whether the bundle gets simulated. All other fields will be omitted except
65    /// simulated field if API didn't receive bundle
66    pub is_simulated: bool,
67    /// time at which the bundle API received the bundle
68    pub received_at: String,
69}
70
71/// Response for `flashbots_getBundleStatsV2` represents stats for a single bundle
72///
73/// Note: this is V2: <https://docs.flashbots.net/flashbots-auction/searchers/advanced/rpc-endpoint#flashbots_getbundlestatsv2>
74///
75/// Timestamp format: "2022-10-06T21:36:06.322Z
76#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77#[serde(rename_all = "camelCase")]
78pub struct StatsSimulated {
79    /// boolean representing if this searcher has a high enough reputation to be in the high
80    /// priority queue
81    pub is_high_priority: bool,
82    /// representing whether the bundle gets simulated. All other fields will be omitted except
83    /// simulated field if API didn't receive bundle
84    pub is_simulated: bool,
85    /// time at which the bundle gets simulated
86    pub simulated_at: String,
87    /// time at which the bundle API received the bundle
88    pub received_at: String,
89    /// indicates time at which each builder selected the bundle to be included in the target
90    /// block
91    #[serde(default)]
92    pub considered_by_builders_at: Vec<ConsideredByBuildersAt>,
93    /// indicates time at which each builder sealed a block containing the bundle
94    #[serde(default)]
95    pub sealed_by_builders_at: Vec<SealedByBuildersAt>,
96}
97
98/// Response for `flashbots_getUserStatsV2` represents stats for a searcher.
99///
100/// Note: this is V2: <https://docs.flashbots.net/flashbots-auction/searchers/advanced/rpc-endpoint#flashbots_getuserstatsv2>
101#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
102#[serde(rename_all = "camelCase")]
103pub struct UserStats {
104    /// Represents whether this searcher has a high enough reputation to be in the high priority
105    /// queue.
106    pub is_high_priority: bool,
107    /// The total amount paid to validators over all time.
108    #[serde(with = "u256_numeric_string")]
109    pub all_time_validator_payments: U256,
110    /// The total amount of gas simulated across all bundles submitted to Flashbots.
111    /// This is the actual gas used in simulations, not gas limit.
112    #[serde(with = "u256_numeric_string")]
113    pub all_time_gas_simulated: U256,
114    /// The total amount paid to validators the last 7 days.
115    #[serde(with = "u256_numeric_string")]
116    pub last_7d_validator_payments: U256,
117    /// The total amount of gas simulated across all bundles submitted to Flashbots in the last 7
118    /// days. This is the actual gas used in simulations, not gas limit.
119    #[serde(with = "u256_numeric_string")]
120    pub last_7d_gas_simulated: U256,
121    /// The total amount paid to validators the last day.
122    #[serde(with = "u256_numeric_string")]
123    pub last_1d_validator_payments: U256,
124    /// The total amount of gas simulated across all bundles submitted to Flashbots in the last
125    /// day. This is the actual gas used in simulations, not gas limit.
126    #[serde(with = "u256_numeric_string")]
127    pub last_1d_gas_simulated: U256,
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133    use similar_asserts::assert_eq;
134
135    use crate::SealedByBuildersAt;
136
137    #[test]
138    fn can_serialize_deserialize_bundle_stats() {
139        let fixtures = [
140            (
141                r#"{
142                    "isSimulated": false
143                }"#,
144                BundleStats::Unknown,
145            ),
146            (
147                r#"{
148                    "isHighPriority": false,
149                    "isSimulated": false,
150                    "receivedAt": "476190476193"
151                }"#,
152                BundleStats::Seen(StatsSeen {
153                    is_high_priority: false,
154                    is_simulated: false,
155                    received_at: "476190476193".to_string(),
156                }),
157            ),
158            (
159                r#"{
160                    "isHighPriority": true,
161                    "isSimulated": true,
162                    "simulatedAt": "111",
163                    "receivedAt": "222",
164                    "consideredByBuildersAt":[],
165                    "sealedByBuildersAt": [
166                        {
167                            "pubkey": "333",
168                            "timestamp": "444"
169                        },
170                        {
171                            "pubkey": "555",
172                            "timestamp": "666"
173                        }
174                    ]
175                }"#,
176                BundleStats::Simulated(StatsSimulated {
177                    is_high_priority: true,
178                    is_simulated: true,
179                    simulated_at: String::from("111"),
180                    received_at: String::from("222"),
181                    considered_by_builders_at: vec![],
182                    sealed_by_builders_at: vec![
183                        SealedByBuildersAt {
184                            pubkey: String::from("333"),
185                            timestamp: String::from("444"),
186                        },
187                        SealedByBuildersAt {
188                            pubkey: String::from("555"),
189                            timestamp: String::from("666"),
190                        },
191                    ],
192                }),
193            ),
194        ];
195
196        let strip_whitespaces =
197            |input: &str| input.chars().filter(|&c| !c.is_whitespace()).collect::<String>();
198
199        for (serialized, deserialized) in fixtures {
200            // Check de-serialization
201            let deserialized_expected = serde_json::from_str::<BundleStats>(serialized).unwrap();
202            assert_eq!(deserialized, deserialized_expected);
203
204            // Check serialization
205            let serialized_expected = &serde_json::to_string(&deserialized).unwrap();
206            assert_eq!(strip_whitespaces(serialized), strip_whitespaces(serialized_expected));
207        }
208    }
209}
210
211#[cfg(test)]
212mod missing_field_tests {
213    use super::*;
214
215    #[test]
216    fn bundle_stats_without_is_simulated_is_an_error() {
217        let res =
218            serde_json::from_str::<BundleStats>(r#"{"isHighPriority":false,"receivedAt":"222"}"#);
219        assert!(res.unwrap_err().to_string().contains("isSimulated"));
220    }
221}