stratus/eth/primitives/
address.rsuse std::fmt::Display;
use std::ops::Deref;
use std::str::FromStr;
use anyhow::anyhow;
use display_json::DebugAsJson;
use ethereum_types::H160;
use ethereum_types::H256;
use fake::Dummy;
use fake::Faker;
use hex_literal::hex;
use crate::alias::RevmAddress;
use crate::eth::primitives::LogTopic;
use crate::gen_newtype_from;
#[derive(DebugAsJson, Clone, Copy, Default, Eq, PartialEq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]
pub struct Address(pub H160);
impl Address {
pub const ZERO: Address = Address(H160::zero());
pub const COINBASE: Address = Address(H160(hex!("00000000000000000000000000000000000000ff")));
pub const BRLC: Address = Address(H160(hex!("a9a55a81a4c085ec0c31585aed4cfb09d78dfd53")));
pub const fn new(bytes: [u8; 20]) -> Self {
Self(H160(bytes))
}
pub fn is_zero(&self) -> bool {
self == &Self::ZERO
}
pub fn is_coinbase(&self) -> bool {
self == &Self::COINBASE
}
pub fn is_ignored(&self) -> bool {
self.is_coinbase() || self.is_zero()
}
}
impl Display for Address {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", const_hex::encode_prefixed(self.0))
}
}
impl Dummy<Faker> for Address {
fn dummy_with_rng<R: rand_core::RngCore + ?Sized>(_: &Faker, rng: &mut R) -> Self {
H160::random_using(rng).into()
}
}
impl Deref for Address {
type Target = H160;
fn deref(&self) -> &Self::Target {
&self.0
}
}
gen_newtype_from!(self = Address, other = H160, [u8; 20]);
impl From<RevmAddress> for Address {
fn from(value: RevmAddress) -> Self {
Address(value.0 .0.into())
}
}
impl From<LogTopic> for Address {
fn from(value: LogTopic) -> Self {
Self(H160::from_slice(&value.0 .0[12..32]))
}
}
impl TryFrom<Vec<u8>> for Address {
type Error = anyhow::Error;
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
if value.len() != 20 {
return Err(anyhow!("array of bytes to be converted to address must have exactly 20 bytes"));
}
Ok(Self(H160::from_slice(&value)))
}
}
impl FromStr for Address {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(H160::from_str(s)?))
}
}
impl From<Address> for H160 {
fn from(value: Address) -> Self {
value.0
}
}
impl From<Address> for RevmAddress {
fn from(value: Address) -> Self {
revm::primitives::Address(value.0 .0.into())
}
}
impl From<Address> for LogTopic {
fn from(value: Address) -> Self {
Self(H256::from(value.0))
}
}