Skip to content

Commit

Permalink
feat: impl From<EthAddress> for StarkFelt (#164)
Browse files Browse the repository at this point in the history
* feat: impl From<EthAddress> for StarkFelt

* add safety comment on new_unchecked

* improve docstrings
  • Loading branch information
tdelabro authored Jan 11, 2024
1 parent b594d74 commit 10a5b78
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
/logs
/target
/Cargo.lock
*.DS_Store
9 changes: 9 additions & 0 deletions src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,15 @@ impl TryFrom<StarkFelt> for EthAddress {
}
}

impl From<EthAddress> for StarkFelt {
fn from(value: EthAddress) -> Self {
let mut bytes = [0u8; 32];
// Padding H160 with zeros to 32 bytes (big endian)
bytes[12..32].copy_from_slice(value.0.as_bytes());
StarkFelt::new_unchecked(bytes)
}
}

impl TryFrom<PrefixedBytesAsHex<20_usize>> for EthAddress {
type Error = StarknetApiError;
fn try_from(val: PrefixedBytesAsHex<20_usize>) -> Result<Self, Self::Error> {
Expand Down
18 changes: 18 additions & 0 deletions src/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,24 @@ impl StarkFelt {
Err(StarknetApiError::OutOfRange { string: hex_str_from_bytes::<32, true>(bytes) })
}

/// Returns a new *unchecked* [`StarkFelt`]
///
/// # Safety
///
/// To avoid undefined behavior, refer to [`StarkFelt`] struct's docstring
/// for the required constraints on the `bytes` argument, or use [`StarkFelt::new`] instead of
/// this method.
///
/// # Usage
///
/// Most of the time you should use `new` instead, but it comes in handy for a few cases:
/// - creating instances of `StarkFelt` at compile time
/// - implementing `From<T> for StarkFelt` for types that have a smaller binary representation
/// than `StarkFelt`
pub const fn new_unchecked(bytes: [u8; 32]) -> StarkFelt {
Self(bytes)
}

/// [StarkFelt] constant that's equal to 0.
pub const ZERO: Self = { Self::from_u128(0_u128) };

Expand Down

0 comments on commit 10a5b78

Please sign in to comment.