use std::borrow::Cow;
use alloy_dyn_abi::{DynSolValue, TypedData};
use alloy_primitives::Address;
use alloy_sol_types::Eip712Domain;
use serde_json::json;
use super::eip712::{self, Schema};
pub(crate) const PRIMARY: &str = "HyperliquidTransaction:SendAsset";
pub(crate) const FIELDS: [(&str, &str); 8] = [
("hyperliquidChain", "string"),
("destination", "string"),
("sourceDex", "string"),
("destinationDex", "string"),
("token", "string"),
("amount", "string"),
("fromSubAccount", "string"),
("nonce", "uint64"),
];
pub(crate) const SIGNATURE_CHAIN_ID: u64 = 999;
pub(crate) fn domain() -> Eip712Domain {
eip712::domain("HyperliquidSignTransaction", "1", SIGNATURE_CHAIN_ID, Some(Address::ZERO))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SendAsset {
pub(crate) hyperliquid_chain: String,
pub(crate) destination: String,
pub(crate) source_dex: String,
pub(crate) destination_dex: String,
pub(crate) token: String,
pub(crate) amount: String,
pub(crate) from_sub_account: String,
pub(crate) nonce: u64,
}
impl SendAsset {
pub(crate) fn typed_data(&self) -> TypedData {
eip712::custom_typed(
domain(),
PRIMARY,
&FIELDS,
json!({
"hyperliquidChain": self.hyperliquid_chain,
"destination": self.destination,
"sourceDex": self.source_dex,
"destinationDex": self.destination_dex,
"token": self.token,
"amount": self.amount,
"fromSubAccount": self.from_sub_account,
"nonce": self.nonce,
}),
)
}
}
impl Schema for SendAsset {
const PRIMARY: &'static str = PRIMARY;
fn encode_type() -> Cow<'static, str> {
eip712::custom_encode_type(PRIMARY, &FIELDS)
}
fn decode(value: &DynSolValue) -> Option<Self> {
let (_, _, values) = value.as_custom_struct()?;
let [chain, destination, source_dex, destination_dex, token, amount, sub_account, nonce] =
values
else {
return None;
};
let text = |value: &DynSolValue| value.as_str().map(str::to_owned);
let (nonce, _) = nonce.as_uint()?;
Some(Self {
hyperliquid_chain: text(chain)?,
destination: text(destination)?,
source_dex: text(source_dex)?,
destination_dex: text(destination_dex)?,
token: text(token)?,
amount: text(amount)?,
from_sub_account: text(sub_account)?,
nonce: u64::try_from(nonce).ok()?,
})
}
}
pub(crate) fn is_system_address(text: &str) -> bool {
let lower = text.to_ascii_lowercase();
lower.starts_with(concat!("0x2", "0000000000", "0000000000", "0000000000", "0000"))
|| lower == format!("0x{}", "22".repeat(20))
}
#[cfg(test)]
mod tests;