Skip to main content

df_hyperliquid_core/utils/
address.rs

1//! The 20-byte account [`Address`] and its `0x` hex form.
2
3use std::{fmt, str::FromStr};
4
5use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
6
7/// Twenty bytes. Read in either case, written lowercase, which is the only
8/// form the venue hashes.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
10pub struct Address([u8; 20]);
11
12/// Text that is not `0x` and forty hex digits; holds the text given, trimmed.
13#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
14#[error("`{0}` is not a 20-byte hex address")]
15pub struct BadAddress(String);
16
17impl Address {
18    /// `0x0000000000000000000000000000000000000000`.
19    pub const ZERO: Address = Address([0u8; 20]);
20
21    /// The address with these 20 bytes.
22    #[must_use]
23    pub const fn from_bytes(bytes: [u8; 20]) -> Self {
24        Address(bytes)
25    }
26
27    /// The 20 bytes.
28    #[must_use]
29    pub const fn bytes(&self) -> &[u8; 20] {
30        &self.0
31    }
32
33    /// Whether this is [`Address::ZERO`].
34    #[must_use]
35    pub fn is_zero(&self) -> bool {
36        *self == Address::ZERO
37    }
38
39    /// For constants: `0x` and forty hex digits in either case, or `None`.
40    #[must_use]
41    pub const fn parse_const(text: &str) -> Option<Address> {
42        let raw = text.as_bytes();
43        if raw.len() != 42 || raw[0] != b'0' || (raw[1] != b'x' && raw[1] != b'X') {
44            return None;
45        }
46        let mut bytes = [0u8; 20];
47        let mut at = 0;
48        while at < 20 {
49            let (Some(high), Some(low)) = (hex_digit(raw[2 + at * 2]), hex_digit(raw[3 + at * 2])) else {
50                return None;
51            };
52            bytes[at] = (high << 4) | low;
53            at += 1;
54        }
55        Some(Address(bytes))
56    }
57
58    /// The lowercase `0x` form the venue's JSON expects.
59    #[must_use]
60    pub fn to_hex(self) -> String {
61        crate::utils::hex::encode_prefixed(&self.0)
62    }
63}
64
65const fn hex_digit(byte: u8) -> Option<u8> {
66    match byte {
67        b'0'..=b'9' => Some(byte - b'0'),
68        b'a'..=b'f' => Some(byte - b'a' + 10),
69        b'A'..=b'F' => Some(byte - b'A' + 10),
70        _ => None,
71    }
72}
73
74impl FromStr for Address {
75    type Err = BadAddress;
76
77    fn from_str(text: &str) -> Result<Self, Self::Err> {
78        let raw = text.trim();
79        Address::parse_const(raw).ok_or_else(|| BadAddress(raw.to_owned()))
80    }
81}
82
83impl fmt::Display for Address {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        f.write_str(&self.to_hex())
86    }
87}
88
89impl Serialize for Address {
90    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
91        serializer.collect_str(self)
92    }
93}
94
95impl<'de> Deserialize<'de> for Address {
96    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
97        let text = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
98        text.parse().map_err(de::Error::custom)
99    }
100}
101
102#[cfg(test)]
103#[path = "tests/address.rs"]
104mod tests;