Skip to content

Commit

Permalink
migrate to the new felt type
Browse files Browse the repository at this point in the history
  • Loading branch information
kariy committed Jun 20, 2024
1 parent fcea566 commit 307e376
Show file tree
Hide file tree
Showing 18 changed files with 372 additions and 541 deletions.
224 changes: 47 additions & 177 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ camino = { version = "1.1.2", features = [ "serde1" ] }
convert_case = "0.6.0"
serde = { version = "1.0", default-features = false, features = ["alloc"] }
serde_json = { version = "1.0", default-features = false, features = ["std"] }
starknet = "0.10.0"
starknet = "0.11.0"
thiserror = "1.0"
tracing = "0.1.34"
tracing-subscriber = { version = "0.3.16", features = [ "env-filter", "json" ] }
Expand Down
2 changes: 1 addition & 1 deletion crates/cairo-serde/src/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ where
T::cairo_deserialize(&r, 0)
}

pub async fn raw_call(self) -> CairoResult<Vec<starknet::core::types::FieldElement>> {
pub async fn raw_call(self) -> CairoResult<Vec<starknet::core::types::Felt>> {
self.provider
.call(self.call_raw, self.block_id)
.await
Expand Down
7 changes: 3 additions & 4 deletions crates/cairo-serde/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use super::CairoSerde;

use starknet::core::types::FieldElement;
use starknet::providers::ProviderError;
use starknet::{core::types::Felt, providers::ProviderError};

/// Cairo types result.
pub type Result<T> = core::result::Result<T, Error>;
Expand All @@ -26,11 +25,11 @@ pub enum Error {
impl CairoSerde for Error {
type RustType = Self;

fn cairo_serialize(_rust: &Self::RustType) -> Vec<FieldElement> {
fn cairo_serialize(_rust: &Self::RustType) -> Vec<Felt> {
vec![]
}

fn cairo_deserialize(_felts: &[FieldElement], _offset: usize) -> Result<Self::RustType> {
fn cairo_deserialize(_felts: &[Felt], _offset: usize) -> Result<Self::RustType> {
Ok(Error::Deserialize(
"Error cairotype deserialized?".to_string(),
))
Expand Down
10 changes: 5 additions & 5 deletions crates/cairo-serde/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub use types::starknet::*;
pub use types::u256::*;
pub use types::*;

use ::starknet::core::types::FieldElement;
use ::starknet::core::types::Felt;

/// Basic cairo structs that are already implemented inside
/// this crate and hence skipped during ABI generation.
Expand Down Expand Up @@ -56,12 +56,12 @@ pub trait CairoSerde {
Self::SERIALIZED_SIZE.unwrap()
}

/// Serializes the given type into a FieldElement sequence.
fn cairo_serialize(rust: &Self::RustType) -> Vec<FieldElement>;
/// Serializes the given type into a Felt sequence.
fn cairo_serialize(rust: &Self::RustType) -> Vec<Felt>;

/// TODO: add `serialize_to(rust: &Self::RustType, out: &mut Vec<FieldElement>)`.
/// TODO: add `serialize_to(rust: &Self::RustType, out: &mut Vec<Felt>)`.
/// for large buffers optimization.
/// Deserializes an array of felts into the given type.
fn cairo_deserialize(felts: &[FieldElement], offset: usize) -> Result<Self::RustType>;
fn cairo_deserialize(felts: &[Felt], offset: usize) -> Result<Self::RustType>;
}
68 changes: 30 additions & 38 deletions crates/cairo-serde/src/types/array.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! CairoSerde implementation for `Vec`.
//! They are used for Array and Span cairo types.
use crate::{CairoSerde, Error, Result};
use starknet::core::types::FieldElement;
use starknet::core::types::Felt;

impl<T, RT> CairoSerde for Vec<T>
where
Expand All @@ -18,13 +18,13 @@ where
1 + data.iter().map(T::cairo_serialized_size).sum::<usize>()
}

fn cairo_serialize(rust: &Self::RustType) -> Vec<FieldElement> {
let mut out: Vec<FieldElement> = vec![rust.len().into()];
fn cairo_serialize(rust: &Self::RustType) -> Vec<Felt> {
let mut out: Vec<Felt> = vec![rust.len().into()];
rust.iter().for_each(|r| out.extend(T::cairo_serialize(r)));
out
}

fn cairo_deserialize(felts: &[FieldElement], offset: usize) -> Result<Self::RustType> {
fn cairo_deserialize(felts: &[Felt], offset: usize) -> Result<Self::RustType> {
if offset >= felts.len() {
return Err(Error::Deserialize(format!(
"Buffer too short to deserialize an array: offset ({}) : buffer {:?}",
Expand Down Expand Up @@ -70,19 +70,15 @@ mod tests {
let v: Vec<u32> = vec![1, 2, 3];
let felts = Vec::<u32>::cairo_serialize(&v);
assert_eq!(felts.len(), 4);
assert_eq!(felts[0], FieldElement::from(3_u32));
assert_eq!(felts[1], FieldElement::ONE);
assert_eq!(felts[2], FieldElement::TWO);
assert_eq!(felts[3], FieldElement::THREE);
assert_eq!(felts[0], Felt::from(3_u32));
assert_eq!(felts[1], Felt::ONE);
assert_eq!(felts[2], Felt::TWO);
assert_eq!(felts[3], Felt::THREE);
}

#[test]
fn test_deserialize_array() {
let felts: Vec<FieldElement> = vec![
FieldElement::from(2_u32),
FieldElement::from(123_u32),
FieldElement::from(9988_u32),
];
let felts: Vec<Felt> = vec![Felt::from(2_u32), Felt::from(123_u32), Felt::from(9988_u32)];

let vals = Vec::<u32>::cairo_deserialize(&felts, 0).unwrap();
assert_eq!(vals.len(), 2);
Expand All @@ -95,23 +91,23 @@ mod tests {
let v: Vec<Vec<u32>> = vec![vec![1, 2], vec![3]];
let felts = Vec::<Vec<u32>>::cairo_serialize(&v);
assert_eq!(felts.len(), 6);
assert_eq!(felts[0], FieldElement::TWO);
assert_eq!(felts[1], FieldElement::TWO);
assert_eq!(felts[2], FieldElement::ONE);
assert_eq!(felts[3], FieldElement::TWO);
assert_eq!(felts[4], FieldElement::ONE);
assert_eq!(felts[5], FieldElement::THREE);
assert_eq!(felts[0], Felt::TWO);
assert_eq!(felts[1], Felt::TWO);
assert_eq!(felts[2], Felt::ONE);
assert_eq!(felts[3], Felt::TWO);
assert_eq!(felts[4], Felt::ONE);
assert_eq!(felts[5], Felt::THREE);
}

#[test]
fn test_deserialize_array_nested() {
let felts: Vec<FieldElement> = vec![
FieldElement::TWO,
FieldElement::TWO,
FieldElement::ONE,
FieldElement::TWO,
FieldElement::ONE,
FieldElement::THREE,
let felts: Vec<Felt> = vec![
Felt::TWO,
Felt::TWO,
Felt::ONE,
Felt::TWO,
Felt::ONE,
Felt::THREE,
];

let vals = Vec::<Vec<u32>>::cairo_deserialize(&felts, 0).unwrap();
Expand All @@ -122,24 +118,20 @@ mod tests {

#[test]
fn test_serialize_array_tuple() {
let v: Vec<(u32, FieldElement)> = vec![(12, FieldElement::TWO)];
let felts = Vec::<(u32, FieldElement)>::cairo_serialize(&v);
let v: Vec<(u32, Felt)> = vec![(12, Felt::TWO)];
let felts = Vec::<(u32, Felt)>::cairo_serialize(&v);
assert_eq!(felts.len(), 3);
assert_eq!(felts[0], FieldElement::from(1_u32));
assert_eq!(felts[1], FieldElement::from(12_u32));
assert_eq!(felts[2], FieldElement::TWO);
assert_eq!(felts[0], Felt::from(1_u32));
assert_eq!(felts[1], Felt::from(12_u32));
assert_eq!(felts[2], Felt::TWO);
}

#[test]
fn test_deserialize_array_tuple() {
let felts: Vec<FieldElement> = vec![
FieldElement::from(1_u32),
FieldElement::from(12_u32),
FieldElement::TWO,
];
let felts: Vec<Felt> = vec![Felt::from(1_u32), Felt::from(12_u32), Felt::TWO];

let vals = Vec::<(u32, FieldElement)>::cairo_deserialize(&felts, 0).unwrap();
let vals = Vec::<(u32, Felt)>::cairo_deserialize(&felts, 0).unwrap();
assert_eq!(vals.len(), 1);
assert_eq!(vals[0], (12, FieldElement::TWO));
assert_eq!(vals[0], (12, Felt::TWO));
}
}
18 changes: 9 additions & 9 deletions crates/cairo-serde/src/types/array_legacy.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Dedicated struct for cairo 0 arrays, where len is not prefixed.
use crate::{CairoSerde, Error, Result};
use starknet::core::types::FieldElement;
use starknet::core::types::Felt;

#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)]
pub struct CairoArrayLegacy<T>(pub Vec<T>);
Expand Down Expand Up @@ -40,15 +40,15 @@ where
data.iter().map(T::cairo_serialized_size).sum::<usize>()
}

fn cairo_serialize(rust: &Self::RustType) -> Vec<FieldElement> {
let mut out: Vec<FieldElement> = vec![];
fn cairo_serialize(rust: &Self::RustType) -> Vec<Felt> {
let mut out: Vec<Felt> = vec![];
rust.0
.iter()
.for_each(|r| out.extend(T::cairo_serialize(r)));
out
}

fn cairo_deserialize(felts: &[FieldElement], offset: usize) -> Result<Self::RustType> {
fn cairo_deserialize(felts: &[Felt], offset: usize) -> Result<Self::RustType> {
if offset >= felts.len() {
// As the length of cairo 0 arrays is not included in the serialized form of the array,
// we don't have much choice here to return an empty array instead of an error.
Expand All @@ -59,15 +59,15 @@ where
let mut offset = offset;
let len = felts[offset - 1];

if FieldElement::from(offset) + len > FieldElement::from(felts.len()) {
if Felt::from(offset) + len > Felt::from(felts.len()) {
return Err(Error::Deserialize(format!(
"Buffer too short to deserialize an array of length {}: offset ({}) : buffer {:?}",
len, offset, felts,
)));
}

loop {
if FieldElement::from(out.len()) == len {
if Felt::from(out.len()) == len {
break;
}

Expand All @@ -88,7 +88,7 @@ mod tests {
#[test]
fn array_offset_len_ok() {
let serialized = vec![felt!("4"), felt!("1"), felt!("2"), felt!("3"), felt!("4")];
let a = CairoArrayLegacy::<FieldElement>::cairo_deserialize(&serialized, 1).unwrap();
let a = CairoArrayLegacy::<Felt>::cairo_deserialize(&serialized, 1).unwrap();
assert_eq!(a.len(), 4);
assert_eq!(a.0[0], felt!("1"));
assert_eq!(a.0[1], felt!("2"));
Expand All @@ -100,7 +100,7 @@ mod tests {
fn empty_array() {
// Array with only the length that is 0 (an other field as we're in cairo 0).
// So the deserialization of the array starts at index 1.
let serialized = vec![FieldElement::ZERO];
let _a = CairoArrayLegacy::<FieldElement>::cairo_deserialize(&serialized, 1).unwrap();
let serialized = vec![Felt::ZERO];
let _a = CairoArrayLegacy::<Felt>::cairo_deserialize(&serialized, 1).unwrap();
}
}
16 changes: 8 additions & 8 deletions crates/cairo-serde/src/types/boolean.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
//! CairoSerde implementation for bool.
use crate::{CairoSerde, Error, Result};
use starknet::core::types::FieldElement;
use starknet::core::types::Felt;

impl CairoSerde for bool {
type RustType = Self;

fn cairo_serialize(rust: &Self::RustType) -> Vec<FieldElement> {
vec![FieldElement::from(*rust as u32)]
fn cairo_serialize(rust: &Self::RustType) -> Vec<Felt> {
vec![Felt::from(*rust as u32)]
}

fn cairo_deserialize(felts: &[FieldElement], offset: usize) -> Result<Self::RustType> {
fn cairo_deserialize(felts: &[Felt], offset: usize) -> Result<Self::RustType> {
if offset >= felts.len() {
return Err(Error::Deserialize(format!(
"Buffer too short to deserialize a boolean: offset ({}) : buffer {:?}",
offset, felts,
)));
}

if felts[offset] == FieldElement::ONE {
if felts[offset] == Felt::ONE {
Ok(true)
} else {
Ok(false)
Expand All @@ -34,17 +34,17 @@ mod tests {
let v = true;
let felts = bool::cairo_serialize(&v);
assert_eq!(felts.len(), 1);
assert_eq!(felts[0], FieldElement::ONE);
assert_eq!(felts[0], Felt::ONE);

let v = false;
let felts = bool::cairo_serialize(&v);
assert_eq!(felts.len(), 1);
assert_eq!(felts[0], FieldElement::ZERO);
assert_eq!(felts[0], Felt::ZERO);
}

#[test]
fn test_deserialize_bool() {
let felts = vec![FieldElement::ZERO, FieldElement::ONE, FieldElement::TWO];
let felts = vec![Felt::ZERO, Felt::ONE, Felt::TWO];
assert!(!bool::cairo_deserialize(&felts, 0).unwrap());
assert!(bool::cairo_deserialize(&felts, 1).unwrap());
assert!(!bool::cairo_deserialize(&felts, 2).unwrap());
Expand Down
Loading

0 comments on commit 307e376

Please sign in to comment.