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: workaround for WithOtherFields #495

Merged
merged 5 commits into from
Apr 9, 2024
Merged
Changes from all commits
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
65 changes: 64 additions & 1 deletion crates/rpc-types/src/with_other.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use crate::{other::OtherFields, TransactionRequest};
use alloy_consensus::{TxEnvelope, TypedTransaction};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::ops::{Deref, DerefMut};

/// Wrapper allowing to catch all fields missing on the inner struct while
/// deserialize.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize)]
pub struct WithOtherFields<T> {
/// The inner struct.
#[serde(flatten)]
Expand Down Expand Up @@ -53,3 +54,65 @@ impl<T: Default> Default for WithOtherFields<T> {
WithOtherFields::new(T::default())
}
}

impl<'de, T> Deserialize<'de> for WithOtherFields<T>
where
T: Deserialize<'de> + Serialize,
{
fn deserialize<D>(deserializer: D) -> Result<WithOtherFields<T>, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;

#[derive(Deserialize)]
struct WithOtherFieldsHelper<T> {
#[serde(flatten)]
inner: T,
#[serde(flatten)]
other: OtherFields,
}

let mut helper = WithOtherFieldsHelper::deserialize(deserializer)?;
// remove all fields present in the inner struct from the other fields, this is to avoid
// duplicate fields in the catch all other fields because serde flatten does not exclude
// already deserialized fields when deserializing the other fields.
if let Value::Object(map) = serde_json::to_value(&helper.inner).map_err(D::Error::custom)? {
for key in map.keys() {
helper.other.remove(key);
}
}

Ok(WithOtherFields { inner: helper.inner, other: helper.other })
}
}

#[cfg(test)]
mod tests {
use std::collections::BTreeMap;

use super::*;
use serde_json::json;

#[derive(Serialize, Deserialize)]
struct Inner {
a: u64,
}

#[derive(Serialize, Deserialize)]
struct InnerWrapper {
#[serde(flatten)]
inner: Inner,
}

#[test]
fn test_correct_other() {
let with_other: WithOtherFields<InnerWrapper> =
serde_json::from_str("{\"a\": 1, \"b\": 2}").unwrap();
assert_eq!(with_other.inner.inner.a, 1);
assert_eq!(
with_other.other,
OtherFields::new(BTreeMap::from_iter(vec![("b".to_string(), json!(2))]))
);
}
}
Loading