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

Move SerializeForVersion to dto module and remove wrapper structs around common types #2459

Merged
merged 3 commits into from
Jan 10, 2025
Merged
Show file tree
Hide file tree
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
8 changes: 8 additions & 0 deletions crates/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,10 @@ macros::i64_backed_u64::serdes!(TransactionIndex);
#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize, Serialize, Default, Dummy)]
pub struct GasPrice(pub u128);

/// A hex representation of a [GasPrice].
#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize, Serialize, Default, Dummy)]
pub struct GasPriceHex(pub GasPrice);

/// Starknet resource bound: amount.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize, Serialize, Default, Dummy)]
pub struct ResourceAmount(pub u64);
Expand All @@ -178,6 +182,10 @@ pub struct ResourceAmount(pub u64);
#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize, Serialize, Default, Dummy)]
pub struct Tip(pub u64);

// A hex representation of a [Tip].
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default, Dummy)]
pub struct TipHex(pub Tip);

/// Starknet resource bound: price per unit.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize, Serialize, Default, Dummy)]
pub struct ResourcePricePerUnit(pub u128);
Expand Down
1 change: 1 addition & 0 deletions crates/common/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ macro_rules! felt {
($hex:expr) => {{
// This forces const evaluation of the macro call. Without this the invocation
// will only be evaluated at runtime.
use ::pathfinder_crypto;
t00ts marked this conversation as resolved.
Show resolved Hide resolved
const CONST_FELT: pathfinder_crypto::Felt =
match pathfinder_crypto::Felt::from_hex_str($hex) {
Ok(f) => f,
Expand Down
4 changes: 2 additions & 2 deletions crates/executor/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use pathfinder_crypto::Felt;

use super::felt::IntoFelt;

#[derive(Debug, PartialEq, Eq)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct FeeEstimate {
pub l1_gas_consumed: primitive_types::U256,
pub l1_gas_price: primitive_types::U256,
Expand Down Expand Up @@ -85,7 +85,7 @@ impl FeeEstimate {
}
}

#[derive(Debug, Eq, PartialEq)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum PriceUnit {
Wei,
Fri,
Expand Down
279 changes: 276 additions & 3 deletions crates/rpc/src/dto.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![allow(unused)]

use serde::de::{Error, IntoDeserializer};
use serde::de::{Error as SerdeError, IntoDeserializer};

mod block;
mod class;
Expand All @@ -12,8 +12,6 @@ mod simulation;
mod state_update;
mod transaction;

pub mod serialize;

pub use block::*;
pub use class::*;
pub use event::*;
Expand All @@ -26,6 +24,176 @@ pub use transaction::*;

use crate::RpcVersion;

#[derive(Copy, Clone)]
#[cfg_attr(test, derive(Default))]
pub struct Serializer {
pub version: RpcVersion,
}

pub struct SerializeStruct {
pub version: RpcVersion,
fields: serde_json::Map<String, Ok>,
}

type BaseSerializer = serde_json::value::Serializer;
pub(crate) type Ok = <BaseSerializer as serde::Serializer>::Ok;
pub(crate) type Error = <BaseSerializer as serde::Serializer>::Error;

pub trait SerializeForVersion {
fn serialize(&self, serializer: Serializer) -> Result<Ok, Error>;
}

impl SerializeForVersion for serde_json::Value {
fn serialize(&self, _serializer: Serializer) -> Result<Ok, Error> {
Ok(self.clone())
}
}

impl SerializeForVersion for &serde_json::Value {
fn serialize(&self, _serializer: Serializer) -> Result<Ok, Error> {
Ok((*self).clone())
}
}

impl Serializer {
pub fn new(version: RpcVersion) -> Self {
Self { version }
}

pub fn serialize(self, value: &dyn SerializeForVersion) -> Result<Ok, Error> {
value.serialize(self)
}

pub fn serialize_unit(self) -> Result<Ok, Error> {
use serde::Serializer;
BaseSerializer {}.serialize_unit()
}

pub fn serialize_str(self, value: &str) -> Result<Ok, Error> {
use serde::Serializer;
BaseSerializer {}.serialize_str(value)
}

pub fn serialize_i32(self, value: i32) -> Result<Ok, Error> {
use serde::Serializer;
BaseSerializer {}.serialize_i32(value)
}

pub fn serialize_i64(self, value: i64) -> Result<Ok, Error> {
use serde::Serializer;
BaseSerializer {}.serialize_i64(value)
}

pub fn serialize_u32(self, value: u32) -> Result<Ok, Error> {
use serde::Serializer;
BaseSerializer {}.serialize_u32(value)
}

pub fn serialize_u64(self, value: u64) -> Result<Ok, Error> {
use serde::Serializer;
BaseSerializer {}.serialize_u64(value)
}

pub fn serialize_u128(self, value: u128) -> Result<Ok, Error> {
use serde::Serializer;
BaseSerializer {}.serialize_u128(value)
}

pub fn serialize_bool(self, value: bool) -> Result<Ok, Error> {
use serde::Serializer;
BaseSerializer {}.serialize_bool(value)
}

pub fn serialize_struct(self) -> Result<SerializeStruct, Error> {
Ok(SerializeStruct {
version: self.version,
fields: Default::default(),
})
}

pub fn serialize_iter(
self,
len: usize,
values: &mut dyn Iterator<Item = impl SerializeForVersion>,
) -> Result<Ok, Error> {
use serde::ser::SerializeSeq;
use serde::Serializer;

let mut serializer = BaseSerializer {}.serialize_seq(Some(len))?;
for value in values {
let value = self.serialize(&value)?;
serializer.serialize_element(&value)?;
}
serializer.end()
}
}

impl SerializeStruct {
pub fn serialize_field(
&mut self,
key: &'static str,
value: &dyn SerializeForVersion,
) -> Result<(), Error> {
let value = value.serialize(Serializer::new(self.version))?;
self.fields.insert(key.to_owned(), value);
Ok(())
}

pub fn serialize_iter(
&mut self,
key: &'static str,
len: usize,
values: &mut dyn Iterator<Item = impl SerializeForVersion>,
) -> Result<(), Error> {
let seq = Serializer::new(self.version).serialize_iter(len, values)?;
self.serialize_field(key, &seq)
}

/// Skips serialization if it's [`None`].
pub fn serialize_optional(
&mut self,
key: &'static str,
value: Option<impl SerializeForVersion>,
) -> Result<(), Error> {
if let Some(value) = value {
self.serialize_field(key, &value)?;
}

Ok(())
}

/// Serializes optional value as null if it's [`None`].
pub fn serialize_optional_with_null(
&mut self,
key: &'static str,
value: Option<impl SerializeForVersion>,
) -> Result<(), Error> {
if let Some(value) = value {
self.serialize_field(key, &value)?;
} else {
self.serialize_field(key, &serde_json::Value::Null)?;
}

Ok(())
}

pub fn flatten(&mut self, value: &dyn SerializeForVersion) -> Result<(), Error> {
let value = value.serialize(Serializer::new(self.version))?;

if let serde_json::Value::Object(value) = value {
for (k, v) in value {
self.fields.insert(k, v);
}
}

Ok(())
}

pub fn end(self) -> Result<Ok, Error> {
Ok(serde_json::Value::Object(self.fields))
}
}

pub trait DeserializeForVersion: Sized {
fn deserialize(value: Value) -> Result<Self, serde_json::Error>;
}
Expand Down Expand Up @@ -448,3 +616,108 @@ impl Map {
}
}
}

#[cfg(test)]
mod tests {
use serde_json::json;

use super::*;

mod serialize {
use super::*;

#[test]
fn str() {
let encoded = Serializer::default().serialize_str("value").unwrap();
assert_eq!(encoded, json!("value"));
}

#[test]
fn u64() {
let encoded = Serializer::default().serialize_u64(123).unwrap();
assert_eq!(encoded, json!(123));
}

#[test]
fn bool() {
let encoded_true = Serializer::default().serialize_bool(true).unwrap();
assert_eq!(encoded_true, json!(true));

let encoded_false = Serializer::default().serialize_bool(false).unwrap();
assert_eq!(encoded_false, json!(false));
}
}

mod serialize_struct {
use super::*;

#[test]
fn version_carries_over() {
let uut = Serializer::new(RpcVersion::PathfinderV01)
.serialize_struct()
.unwrap();
assert_eq!(uut.version, RpcVersion::PathfinderV01);
}

#[test]
fn optional() {
let mut uut = Serializer::default().serialize_struct().unwrap();
uut.serialize_optional("missing", None::<u64>).unwrap();
uut.serialize_optional("present", Some(200u64)).unwrap();
let encoded = uut.end().unwrap();
let expected = json!({"present": 200u64});

assert_eq!(encoded, expected);
}

#[test]
fn iter() {
let empty = vec![0u64; 0];
let count = vec![0u64, 1, 2, 3];

let mut uut = Serializer::default().serialize_struct().unwrap();
uut.serialize_iter("empty", 0, &mut empty.iter()).unwrap();
uut.serialize_iter("count", 0, &mut count.iter()).unwrap();
let encoded = uut.end().unwrap();
let expected = json!({
"count": count,
"empty": empty,
});

assert_eq!(encoded, expected);
}

#[test]
fn flatten() {
struct TypeX(u64);
impl SerializeForVersion for TypeX {
fn serialize(&self, serializer: Serializer) -> Result<Ok, Error> {
let mut serializer = serializer.serialize_struct()?;
serializer.serialize_field("x", &self.0);
serializer.end()
}
}

let mut uut = Serializer::default().serialize_struct().unwrap();
uut.serialize_field("y", &200u64).unwrap();
uut.flatten(&TypeX(300)).unwrap();
let encoded = uut.end().unwrap();

let expected = json!({
"x": 300,
"y": 200,
});

assert_eq!(encoded, expected);
}

#[test]
fn field() {
let mut uut = Serializer::default().serialize_struct().unwrap();
uut.serialize_field("field", &"value").unwrap();
let encoded = uut.end().unwrap();
let expected = json!({"field": "value"});
assert_eq!(encoded, expected);
}
}
}
Loading
Loading