use std::{fmt, str::FromStr};
use alloy_primitives::{B256, hex};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
use uuid::Uuid;
const CLIENT_ID_MAX: usize = 64;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct ClientId(String);
impl ClientId {
pub fn new(id: impl Into<String>) -> Result<Self, InvalidClientId> {
let id = id.into();
let allowed = |b: u8| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b':' | b'-');
if id.is_empty() || id.len() > CLIENT_ID_MAX || !id.bytes().all(allowed) {
return Err(InvalidClientId);
}
Ok(Self(id))
}
pub fn generate() -> Self {
Self(Uuid::now_v7().simple().to_string())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for ClientId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl FromStr for ClientId {
type Err = InvalidClientId;
fn from_str(id: &str) -> Result<Self, Self::Err> {
Self::new(id)
}
}
impl<'de> Deserialize<'de> for ClientId {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Self::new(String::deserialize(deserializer)?).map_err(de::Error::custom)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidClientId;
impl fmt::Display for InvalidClientId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("client id must be 1 to 64 characters of [A-Za-z0-9_.:-]")
}
}
impl std::error::Error for InvalidClientId {}
macro_rules! decimal_u64 {
($(#[$meta:meta])* $name:ident) => {
$(#[$meta])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct $name(u64);
impl $name {
pub const fn new(value: u64) -> Self {
Self(value)
}
pub const fn get(self) -> u64 {
self.0
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl FromStr for $name {
type Err = std::num::ParseIntError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
text.parse().map(Self)
}
}
impl Serialize for $name {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(&self.0)
}
}
impl<'de> Deserialize<'de> for $name {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
String::deserialize(deserializer)?.parse().map_err(de::Error::custom)
}
}
};
}
decimal_u64! {
Cursor
}
decimal_u64! {
Revision
}
decimal_u64! {
BlockNumber
}
decimal_u64! {
HyperliquidNonce
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PortfolioRevision {
count: u64,
micros: i64,
}
impl fmt::Display for PortfolioRevision {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.count, self.micros)
}
}
impl FromStr for PortfolioRevision {
type Err = std::num::ParseIntError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let (count, micros) = text.split_once(':').unwrap_or((text, ""));
Ok(Self { count: count.parse()?, micros: micros.parse()? })
}
}
impl Serialize for PortfolioRevision {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for PortfolioRevision {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
String::deserialize(deserializer)?.parse().map_err(de::Error::custom)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PageCursor(String);
impl PageCursor {
pub fn new(cursor: impl Into<String>) -> Self {
Self(cursor.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for PageCursor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
macro_rules! uuid_id {
($(#[$meta:meta])* $name:ident) => {
$(#[$meta])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct $name(Uuid);
impl $name {
pub const fn new(id: Uuid) -> Self {
Self(id)
}
pub const fn as_uuid(&self) -> &Uuid {
&self.0
}
}
impl From<Uuid> for $name {
fn from(id: Uuid) -> Self {
Self(id)
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl FromStr for $name {
type Err = uuid::Error;
fn from_str(text: &str) -> Result<Self, Self::Err> {
text.parse().map(Self)
}
}
};
}
uuid_id! {
TransferId
}
uuid_id! {
TakeId
}
uuid_id! {
FillId
}
uuid_id! {
SessionId
}
uuid_id! {
PreparationId
}
uuid_id! {
QuoteIdentityId
}
uuid_id! {
CloseId
}
uuid_id! {
WithdrawalId
}
uuid_id! {
MoveId
}
uuid_id! {
BridgeId
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct OrderId(B256);
impl OrderId {
pub const fn new(id: B256) -> Self {
Self(id)
}
pub const fn as_b256(&self) -> &B256 {
&self.0
}
}
impl fmt::Display for OrderId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:#x}", self.0)
}
}
impl FromStr for OrderId {
type Err = hex::FromHexError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
text.parse().map(Self)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct SignatureBytes([u8; 65]);
impl SignatureBytes {
pub const fn new(mut bytes: [u8; 65]) -> Option<Self> {
match bytes[64] {
0 | 1 => {
bytes[64] += 27;
Some(Self(bytes))
}
27 | 28 => Some(Self(bytes)),
_ => None,
}
}
pub const fn as_bytes(&self) -> &[u8; 65] {
&self.0
}
}
impl fmt::Debug for SignatureBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("SignatureBytes(****)")
}
}
impl Serialize for SignatureBytes {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&hex::encode_prefixed(self.0))
}
}
impl<'de> Deserialize<'de> for SignatureBytes {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
let digits = text.strip_prefix("0x").ok_or_else(|| de::Error::custom("missing 0x"))?;
let bytes = hex::decode_to_array::<_, 65>(digits).map_err(de::Error::custom)?;
Self::new(bytes).ok_or_else(|| de::Error::custom("signature v must be 0, 1, 27 or 28"))
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ClaimSecret(B256);
impl ClaimSecret {
pub const fn expose_secret(&self) -> &B256 {
&self.0
}
}
impl fmt::Debug for ClaimSecret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ClaimSecret(****)")
}
}
#[cfg(test)]
mod tests;