diff --git a/src/hash.rs b/src/hash.rs index 1c6ed00b..d0e4bfef 100644 --- a/src/hash.rs +++ b/src/hash.rs @@ -7,6 +7,7 @@ use std::io::Error; use serde::{Deserialize, Serialize}; use starknet_crypto::{pedersen_hash as starknet_crypto_pedersen_hash, FieldElement}; +use web3::types::U256; use crate::serde_utils::{ bytes_from_hex_str, hex_str_from_bytes, BytesAsHex, NonPrefixedBytesAsHex, PrefixedBytesAsHex, @@ -49,6 +50,24 @@ pub fn pedersen_hash_array(felts: &[StarkFelt]) -> StarkHash { #[serde(try_from = "PrefixedBytesAsHex<32_usize>", into = "PrefixedBytesAsHex<32_usize>")] pub struct StarkFelt([u8; 32]); +#[derive(Clone, Copy, Eq, PartialEq, Default)] +pub struct StarkFeltAsDecimal(U256); + +impl Serialize for StarkFeltAsDecimal { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + serializer.serialize_str(&self.0.to_string()) + } +} + +impl Display for StarkFeltAsDecimal { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0.to_string()) + } +} + impl StarkFelt { /// Returns a new [`StarkFelt`]. pub fn new(bytes: [u8; 32]) -> Result { @@ -201,6 +220,18 @@ impl TryFrom for usize { } } +impl From for U256 { + fn from(felt: StarkFelt) -> Self { + web3::types::U256::from_big_endian(&felt.0) + } +} + +impl From for StarkFeltAsDecimal { + fn from(felt: StarkFelt) -> Self { + StarkFeltAsDecimal(U256::from(felt)) + } +} + impl Debug for StarkFelt { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.str_format(f) diff --git a/src/hash_test.rs b/src/hash_test.rs index 207a9809..4086c73e 100644 --- a/src/hash_test.rs +++ b/src/hash_test.rs @@ -1,4 +1,4 @@ -use crate::hash::{pedersen_hash, pedersen_hash_array, StarkFelt}; +use crate::hash::{pedersen_hash, pedersen_hash_array, StarkFelt, StarkFeltAsDecimal}; use crate::stark_felt; #[test] @@ -67,3 +67,16 @@ fn hash_serde() { assert_eq!(bytes, d.0); } } + +#[test] +fn stark_felt_from_hex_to_decimal() { + let felt = stark_felt!("0x000000000000d"); + assert_eq!(StarkFeltAsDecimal::from(felt).to_string(), "13"); + + let felt = stark_felt!("0x264d6571d5f186bab2a9d5d8d30aa38bf5502bc4354870edbfe194c6f655c9b"); + let felt_decimal = StarkFeltAsDecimal::from(felt); + assert_eq!( + felt_decimal.to_string(), + "1082789725971120866445625682125121757273101071727151005357998861560691645595" + ); +}