use crate::error::SdkError;
use borsh::{BorshDeserialize, BorshSerialize};
use pyde_crypto::poseidon2::poseidon2_hash;
use serde::{Deserialize, Serialize};
use std::fmt;
use super::hash::Poseidon2Hash;
use super::FalconPubkey;
pub const ADDRESS_LEN: usize = 32;
pub const CREATE2_PREFIX: u8 = 0xFF;
pub const CONTRACT_ADDRESS_PREFIX: &[u8] = b"pyde-contract:";
#[derive(
Clone,
Copy,
Eq,
PartialEq,
Ord,
PartialOrd,
Hash,
BorshSerialize,
BorshDeserialize,
Serialize,
Deserialize,
)]
pub struct Address(pub [u8; ADDRESS_LEN]);
impl Address {
pub const ZERO: Self = Self([0u8; ADDRESS_LEN]);
#[must_use]
pub const fn new(bytes: [u8; ADDRESS_LEN]) -> Self {
Self(bytes)
}
#[must_use]
pub const fn as_bytes(&self) -> &[u8; ADDRESS_LEN] {
&self.0
}
#[must_use]
pub fn is_zero(&self) -> bool {
self.0 == [0u8; ADDRESS_LEN]
}
#[must_use]
pub fn to_hex(&self) -> String {
format!("0x{}", hex::encode(self.0))
}
pub fn from_hex(s: &str) -> Result<Self, SdkError> {
let hex_str = s.trim_start_matches("0x");
if hex_str.len() != 64 {
return Err(SdkError::InvalidAddress(format!(
"expected 64 hex chars, got {}",
hex_str.len()
)));
}
let bytes =
hex::decode(hex_str).map_err(|e| SdkError::InvalidAddress(format!("bad hex: {e}")))?;
let mut out = [0u8; ADDRESS_LEN];
out.copy_from_slice(&bytes);
Ok(Self(out))
}
#[must_use]
pub fn from_pubkey(pubkey: &FalconPubkey) -> Self {
let bytes: [u8; 32] = poseidon2_hash(pubkey.as_bytes()).into();
Self(bytes)
}
#[must_use]
pub fn create(deployer: &Address, nonce: u64) -> Self {
let mut input = [0u8; 40];
input[..32].copy_from_slice(deployer.as_bytes());
input[32..40].copy_from_slice(&nonce.to_le_bytes());
let bytes: [u8; 32] = poseidon2_hash(&input).into();
Self(bytes)
}
#[must_use]
pub fn create2(deployer: &Address, salt: &[u8; 32], code_hash: &Poseidon2Hash) -> Self {
let mut input = [0u8; 97];
input[0] = CREATE2_PREFIX;
input[1..33].copy_from_slice(deployer.as_bytes());
input[33..65].copy_from_slice(salt);
input[65..97].copy_from_slice(code_hash.as_bytes());
let bytes: [u8; 32] = poseidon2_hash(&input).into();
Self(bytes)
}
#[must_use]
pub fn from_contract_name(name: &str) -> Self {
let mut input = Vec::with_capacity(CONTRACT_ADDRESS_PREFIX.len() + name.len());
input.extend_from_slice(CONTRACT_ADDRESS_PREFIX);
input.extend_from_slice(name.as_bytes());
let bytes: [u8; 32] = poseidon2_hash(&input).into();
Self(bytes)
}
}
impl fmt::Debug for Address {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Address({})", self.to_hex())
}
}
impl fmt::Display for Address {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_hex())
}
}
impl From<[u8; ADDRESS_LEN]> for Address {
fn from(bytes: [u8; ADDRESS_LEN]) -> Self {
Self(bytes)
}
}
impl From<Address> for [u8; ADDRESS_LEN] {
fn from(addr: Address) -> Self {
addr.0
}
}
impl AsRef<[u8]> for Address {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl std::str::FromStr for Address {
type Err = SdkError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::from_hex(s)
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use crate::types::FALCON_PUBKEY_LEN;
#[test]
fn zero_address_is_all_zeros() {
assert!(Address::ZERO.is_zero());
assert_eq!(Address::ZERO.0, [0u8; ADDRESS_LEN]);
}
#[test]
fn display_uses_0x_prefix_lowercase() {
let addr = Address::new([0xAB; ADDRESS_LEN]);
let rendered = format!("{addr}");
assert!(rendered.starts_with("0x"));
assert_eq!(rendered.len(), 2 + 64);
assert_eq!(rendered, format!("0x{}", "ab".repeat(ADDRESS_LEN)));
}
#[test]
fn hex_round_trip() {
let addr = Address::new([0x5A; ADDRESS_LEN]);
let parsed = Address::from_hex(&addr.to_hex()).unwrap();
assert_eq!(addr, parsed);
}
#[test]
fn hex_accepts_bare_and_prefixed() {
let bare = "a".repeat(64);
let prefixed = format!("0x{bare}");
let a = Address::from_hex(&bare).unwrap();
let b = Address::from_hex(&prefixed).unwrap();
assert_eq!(a, b);
}
#[test]
fn hex_rejects_wrong_length() {
assert!(Address::from_hex("0xabcd").is_err());
}
#[test]
fn hex_rejects_non_hex() {
let bogus = "z".repeat(64);
assert!(Address::from_hex(&bogus).is_err());
}
#[test]
fn from_pubkey_is_deterministic() {
let pk = FalconPubkey::new([0xAB; FALCON_PUBKEY_LEN]);
assert_eq!(Address::from_pubkey(&pk), Address::from_pubkey(&pk));
}
#[test]
fn from_pubkey_distinguishes_distinct_pubkeys() {
let a = FalconPubkey::new([0x01; FALCON_PUBKEY_LEN]);
let b = FalconPubkey::new([0x02; FALCON_PUBKEY_LEN]);
assert_ne!(Address::from_pubkey(&a), Address::from_pubkey(&b));
}
#[test]
fn create_address_changes_with_nonce() {
let deployer = Address::new([0x42; 32]);
assert_ne!(Address::create(&deployer, 0), Address::create(&deployer, 1));
}
#[test]
fn create2_disjoint_from_create() {
let deployer = Address::new([0x42; 32]);
let create_addr = Address::create(&deployer, 0);
let create2_addr = Address::create2(&deployer, &[0u8; 32], &Poseidon2Hash::zero());
assert_ne!(create_addr, create2_addr);
}
#[test]
fn contract_name_address_disjoint_from_create() {
let deployer = Address::new([0x42; 32]);
assert_ne!(
Address::from_contract_name("counter"),
Address::create(&deployer, 0)
);
}
#[test]
fn borsh_round_trip() {
let addr = Address::new([0x77; ADDRESS_LEN]);
let bytes = borsh::to_vec(&addr).unwrap();
assert_eq!(bytes.len(), ADDRESS_LEN);
let decoded: Address = borsh::from_slice(&bytes).unwrap();
assert_eq!(addr, decoded);
}
#[test]
fn from_str_works() {
use std::str::FromStr;
let s = "0xaabbccddeeff00112233445566778899aabbccddeeff00112233445566778899";
let addr = Address::from_str(s).unwrap();
assert_eq!(addr.to_hex(), s);
}
}