Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(rpc-types): FeeHistory deser #1629

Merged
merged 2 commits into from
Nov 6, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions crates/rpc-types-eth/src/fee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ pub struct FeeHistory {
pub base_fee_per_gas: Vec<u128>,
/// An array of block gas used ratios. These are calculated as the ratio
/// of `gasUsed` and `gasLimit`.
#[cfg_attr(feature = "serde", serde(deserialize_with = "gas_used_ratio_deser::deserialize"))]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe we have this in alloy-serde:

pub fn null_as_default<'de, T, D>(deserializer: D) -> Result<T, D::Error>

pub gas_used_ratio: Vec<f64>,
/// An array of block base fees per blob gas. This includes the next block after the newest
/// of the returned range, because this value can be derived from the newest block. Zeroes
Expand Down Expand Up @@ -112,6 +113,20 @@ impl FeeHistory {
}
}

mod gas_used_ratio_deser {
use serde::{Deserialize, Deserializer};

pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Vec<f64>, D::Error>
where
D: Deserializer<'de>,
{
// First try to deserialize as Option<Vec<f64>>
let opt = Option::<Vec<f64>>::deserialize(deserializer)?;
// Return empty vec if null, otherwise return the vec
Ok(opt.unwrap_or_default())
}
}

#[cfg(test)]
mod tests {
use crate::FeeHistory;
Expand Down Expand Up @@ -148,4 +163,10 @@ mod tests {
let json = r#"{"oldestBlock":"0xdee807","baseFeePerGas":["0x4ccf46253","0x4457de658","0x4531c5aee","0x3cfa33972","0x3d33403eb","0x399457884","0x40bdf9772","0x48d55e7c4","0x51e9ebf14","0x55f460bf9","0x4e31607e4"],"gasUsedRatio":[0.05909575012589385,0.5498182666666667,0.0249864,0.5146185,0.2633512,0.997582061117319,0.999914966153302,0.9986873805040722,0.6973219148223686,0.13879896448917434],"baseFeePerBlobGas":["0x0","0x0","0x0","0x0","0x0","0x0","0x0","0x0","0x0","0x0","0x0"],"blobGasUsedRatio":[0,0,0,0,0,0,0,0,0,0]}"#;
let _actual = serde_json::from_str::<FeeHistory>(json).unwrap();
}

#[test]
fn test_fee_hist_null_gas_used_ratio() {
let json = r#"{"oldestBlock": "0x0", "gasUsedRatio": null}"#;
let _actual = serde_json::from_str::<FeeHistory>(json).unwrap();
}
}
Loading