use alloy_primitives::{Address, U256};
use chrono::{DateTime, Utc};
use serde_json::{Value, json};
use super::{
aster,
checks::{
details::{self, differs, unsupported},
differs_unless, take,
withdrawal::{ASTER_MAX_FEE_UNITS, positive},
},
eip712::{self, Withdraw},
hyperliquid::{self, SendAsset},
polymarket,
};
use crate::{
deployments,
error::VerificationError,
types::{Amount, VenueId},
};
pub const HYPERLIQUID_BRIDGE: Address = deployments::HYPERLIQUID_BRIDGE;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TransferKind {
Withdrawal,
Send,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct VenueTransfer {
pub venue: VenueId,
pub kind: TransferKind,
pub account: Option<Address>,
pub recipient: Option<Address>,
pub chain_id: Option<u64>,
pub amount: Amount,
pub cost: Amount,
pub source_dex: Option<String>,
pub id: Option<String>,
pub signed_at: DateTime<Utc>,
}
const SOURCE_DEXES: [&str; 3] = ["", "spot", "xyz"];
const WITHDRAW_FIELDS: [(&str, &str); 7] = [
("account", "address"),
("token", "address"),
("amount", "uint256"),
("fee", "uint256"),
("to", "address"),
("salt", "uint64"),
("ts", "uint64"),
];
const OP_FIELDS: [(&str, &str); 3] = [("data", "bytes32"), ("salt", "uint64"), ("ts", "uint64")];
const MESSAGE_FIELDS: [(&str, &str); 1] = [("msg", "string")];
const DOMAIN_FIELDS: [(&str, &str); 4] = [
("name", "string"),
("version", "string"),
("chainId", "uint256"),
("verifyingContract", "address"),
];
pub fn read_venue_transfer(
raw: &Value,
venue: &VenueId,
) -> Result<VenueTransfer, VerificationError> {
let primary = raw["primaryType"].as_str();
if primary == Some("Op") && *venue != VenueId::Polymarket {
return Err(differs(details::PRIMARY_TYPE));
}
match venue {
VenueId::Hyperliquid => read_send_asset(raw),
VenueId::Polymarket if primary == Some("Op") => read_internal_transfer(raw),
VenueId::Polymarket => read_polymarket_withdrawal(raw),
VenueId::Aster if primary == Some("Message") => read_aster_send(raw),
VenueId::Aster => read_aster_withdrawal(raw),
_ => Err(unsupported(details::VENUE)),
}
}
fn read_send_asset(raw: &Value) -> Result<VenueTransfer, VerificationError> {
let send = eip712::parse_in::<SendAsset>(raw, &hyperliquid::domain())?.message;
let amount = deployments::decimal_units(&send.amount, deployments::HYPERLIQUID.decimals);
let amount = amount.filter(|units| !units.is_zero()).map(Amount::new);
differs_unless([
(send.hyperliquid_chain == "Mainnet", details::HYPERLIQUID_CHAIN),
(send.token == deployments::HYPERLIQUID_USDC, details::TOKEN),
(send.from_sub_account.is_empty(), details::FROM_SUB_ACCOUNT),
(SOURCE_DEXES.contains(&send.source_dex.as_str()), details::SOURCE_DEX),
(amount.is_some(), details::AMOUNT),
])?;
let amount = amount.ok_or(differs(details::AMOUNT))?;
let signed_at = at_millis(send.nonce)?;
let bridge = format!("{HYPERLIQUID_BRIDGE:#x}");
let (kind, recipient, chain_id) =
if send.destination.eq_ignore_ascii_case(&bridge) && send.destination_dex == "spot" {
(TransferKind::Withdrawal, None, Some(hyperliquid::SIGNATURE_CHAIN_ID))
} else {
let recipient = eip712::address_text(&send.destination)
.filter(|recipient| send.destination == format!("{recipient:#x}"))
.filter(|_| !hyperliquid::is_system_address(&send.destination))
.ok_or(differs(details::DESTINATION))?;
if !["", "spot"].contains(&send.destination_dex.as_str()) {
return Err(differs(details::DESTINATION_DEX));
}
(TransferKind::Send, Some(recipient), None)
};
Ok(VenueTransfer {
venue: VenueId::Hyperliquid,
kind,
account: None,
recipient,
chain_id,
amount,
cost: amount,
source_dex: Some(send.source_dex),
id: None,
signed_at,
})
}
fn read_internal_transfer(raw: &Value) -> Result<VenueTransfer, VerificationError> {
let (parsed, op) = eip712::parse_operation(raw, &polymarket::operation_domain())?;
let transfer = polymarket::InternalTransfer::read(op).ok_or(differs(details::OP))?;
let amount = deployments::decimal_units(&transfer.amount, deployments::POLYMARKET.decimals)
.filter(|units| !units.is_zero())
.map(Amount::new);
let account = eip712::address_text(&transfer.account);
let recipient = eip712::address_text(&transfer.to);
differs_unless([
(account.is_some(), details::ACCOUNT),
(recipient.is_some(), details::TO),
(
eip712::address_text(&transfer.token) == Some(deployments::POLYMARKET.token),
details::TOKEN,
),
(transfer.hash() == Some(parsed.message.data), details::DATA),
])?;
let amount = amount.ok_or(differs(details::AMOUNT))?;
Ok(VenueTransfer {
venue: VenueId::Polymarket,
kind: TransferKind::Send,
account,
recipient,
chain_id: None,
amount,
cost: amount,
source_dex: None,
id: None,
signed_at: at_millis(parsed.message.ts)?,
})
}
fn read_polymarket_withdrawal(raw: &Value) -> Result<VenueTransfer, VerificationError> {
let withdraw = eip712::parse_in::<Withdraw>(raw, &polymarket::withdraw_domain())?.message;
differs_unless([
(withdraw.token == deployments::POLYMARKET.token, details::TOKEN),
(withdraw.fee.is_zero(), details::FEE),
(!withdraw.amount.is_zero(), details::AMOUNT),
])?;
let amount = Amount::new(withdraw.amount);
Ok(VenueTransfer {
venue: VenueId::Polymarket,
kind: TransferKind::Withdrawal,
account: Some(withdraw.account),
recipient: Some(withdraw.to),
chain_id: Some(deployments::POLYMARKET.id),
amount,
cost: amount,
source_dex: None,
id: None,
signed_at: at_seconds(withdraw.ts)?,
})
}
fn read_aster_send(raw: &Value) -> Result<VenueTransfer, VerificationError> {
let (_, transfer, _) = take::aster_transfer(raw)?;
differs_unless([
(is_client_id(&transfer.client_id), details::CLIENT_TRAN_ID),
(!transfer.amount.is_zero(), details::AMOUNT),
])?;
let amount = Amount::new(transfer.amount);
Ok(VenueTransfer {
venue: VenueId::Aster,
kind: TransferKind::Send,
account: Some(transfer.user),
recipient: Some(transfer.to),
chain_id: None,
amount,
cost: amount,
source_dex: None,
id: Some(transfer.client_id),
signed_at: at_micros(transfer.nonce)?,
})
}
fn read_aster_withdrawal(raw: &Value) -> Result<VenueTransfer, VerificationError> {
let withdrawal =
eip712::parse_in::<aster::Withdrawal>(raw, &aster::withdrawal_domain())?.message;
let chain_id = aster::WITHDRAW_CHAINS
.iter()
.find(|(_, name)| *name == withdrawal.destination_chain)
.map(|(id, _)| *id);
let decimals = deployments::ASTER.decimals;
let fee = deployments::decimal_units(&withdrawal.fee, decimals);
let cost = deployments::decimal_units(&withdrawal.amount, decimals);
let max_fee = U256::from(ASTER_MAX_FEE_UNITS) * deployments::ASTER.step();
differs_unless([
(withdrawal.kind == "Withdraw", details::TYPE),
(chain_id.is_some(), details::DESTINATION_CHAIN),
(withdrawal.token == aster::TOKEN, details::TOKEN),
(withdrawal.aster_chain == "Mainnet", details::ASTER_CHAIN),
(fee.is_some_and(|fee| fee <= max_fee), details::FEE),
])?;
let (cost, fee) =
cost.zip(fee).filter(|(cost, fee)| cost > fee).ok_or(differs(details::AMOUNT))?;
let nonce = u64::try_from(withdrawal.nonce).map_err(|_| differs(details::NONCE))?;
Ok(VenueTransfer {
venue: VenueId::Aster,
kind: TransferKind::Withdrawal,
account: Some(withdrawal.destination),
recipient: Some(withdrawal.destination),
chain_id,
amount: Amount::new(cost - fee),
cost: Amount::new(cost),
source_dex: None,
id: None,
signed_at: at_micros(nonce)?,
})
}
pub fn hyperliquid_send_asset(
amount: Amount,
nonce: u64,
source_dex: &str,
recipient: Option<Address>,
) -> Result<Value, VerificationError> {
if !SOURCE_DEXES.contains(&source_dex) {
return Err(differs(details::SOURCE_DEX));
}
let destination = match recipient {
Some(recipient) if hyperliquid::is_system_address(&format!("{recipient:#x}")) => {
return Err(differs(details::RECIPIENT));
}
Some(recipient) => format!("{recipient:#x}"),
None => format!("{HYPERLIQUID_BRIDGE:#x}"),
};
let send = SendAsset {
hyperliquid_chain: "Mainnet".to_owned(),
destination,
source_dex: source_dex.to_owned(),
destination_dex: if recipient.is_some() { String::new() } else { "spot".to_owned() },
token: deployments::HYPERLIQUID_USDC.to_owned(),
amount: decimal_text(positive(amount)?, deployments::HYPERLIQUID.decimals)?,
from_sub_account: String::new(),
nonce: positive_time(nonce)?,
};
let message = json!({
"hyperliquidChain": send.hyperliquid_chain,
"destination": send.destination,
"sourceDex": send.source_dex,
"destinationDex": send.destination_dex,
"token": send.token,
"amount": send.amount,
"fromSubAccount": send.from_sub_account,
"nonce": send.nonce,
});
let domain = domain_json(
"HyperliquidSignTransaction",
hyperliquid::SIGNATURE_CHAIN_ID,
Some(Address::ZERO),
);
Ok(typed_json(&domain, hyperliquid::PRIMARY, &hyperliquid::FIELDS, &message))
}
pub fn polymarket_withdrawal(
account: Address,
recipient: Address,
amount: Amount,
salt: u64,
ts: u64,
) -> Result<Value, VerificationError> {
let message = json!({
"account": account.to_checksum(None),
"token": deployments::POLYMARKET.token.to_checksum(None),
"amount": positive(amount)?.to_string(),
"fee": "0",
"to": recipient.to_checksum(None),
"salt": safe_salt(salt)?,
"ts": positive_time(ts)?,
});
let domain = domain_json(
"Polymarket",
deployments::POLYMARKET.id,
Some(deployments::POLYMARKET_WITHDRAW_CONTRACT),
);
Ok(typed_json(&domain, "Withdraw", &WITHDRAW_FIELDS, &message))
}
pub fn polymarket_send(
account: Address,
recipient: Address,
amount: Amount,
salt: u64,
ts: u64,
) -> Result<Value, VerificationError> {
let transfer = polymarket::InternalTransfer {
account: account.to_checksum(None),
token: deployments::POLYMARKET.token.to_checksum(None),
amount: decimal_text(positive(amount)?, deployments::POLYMARKET.decimals)?,
to: recipient.to_checksum(None),
};
let data = transfer.hash().ok_or(differs(details::OP))?;
let message = json!({
"data": format!("{data:#x}"),
"salt": safe_salt(salt)?,
"ts": positive_time(ts)?,
});
let domain = domain_json("Polymarket", deployments::POLYMARKET.id, None);
let mut typed = typed_json(&domain, "Op", &OP_FIELDS, &message);
typed["op"] = json!({
"type": polymarket::INTERNAL_TRANSFER,
"args": {
"account": transfer.account,
"token": transfer.token,
"amount": transfer.amount,
"to": transfer.to,
},
});
Ok(typed)
}
pub fn aster_withdrawal(
account: Address,
chain_id: u64,
amount: Amount,
fee: Amount,
nonce: u64,
) -> Result<Value, VerificationError> {
let chain = aster::withdraw_chain_name(chain_id).ok_or(differs(details::DESTINATION_CHAIN))?;
let max_fee = U256::from(ASTER_MAX_FEE_UNITS) * deployments::ASTER.step();
if fee.get() > max_fee {
return Err(differs(details::FEE));
}
let cost = positive(amount)?.checked_add(fee.get()).ok_or(differs(details::AMOUNT))?;
let decimals = deployments::ASTER.decimals;
let withdrawal = aster::Withdrawal {
kind: "Withdraw".to_owned(),
destination: account,
destination_chain: chain.to_owned(),
token: aster::TOKEN.to_owned(),
amount: decimal_text(cost, decimals)?,
fee: decimal_text(fee.get(), decimals)?,
nonce: U256::from(micros_nonce(nonce)?),
aster_chain: "Mainnet".to_owned(),
};
let message = json!({
"type": withdrawal.kind,
"destination": format!("{:#x}", withdrawal.destination),
"destination Chain": withdrawal.destination_chain,
"token": withdrawal.token,
"amount": withdrawal.amount,
"fee": withdrawal.fee,
"nonce": withdrawal.nonce.to_string(),
"aster chain": withdrawal.aster_chain,
});
let domain = domain_json("Aster", aster::CHAIN_ID, Some(Address::ZERO));
Ok(typed_json(&domain, aster::WITHDRAWAL_PRIMARY, &aster::WITHDRAWAL_FIELDS, &message))
}
pub fn aster_send(
account: Address,
recipient: Address,
amount: Amount,
id: &str,
nonce: u64,
) -> Result<Value, VerificationError> {
if !is_client_id(id) {
return Err(differs(details::CLIENT_TRAN_ID));
}
let msg = format!(
"asset={}&amount={}&toAddress={}&clientTranId={id}&nonce={}&user={}",
aster::TOKEN,
decimal_text(positive(amount)?, deployments::ASTER.decimals)?,
recipient.to_checksum(None),
micros_nonce(nonce)?,
account.to_checksum(None),
);
let domain = domain_json("AsterSignTransaction", aster::TRANSFER_CHAIN_ID, Some(Address::ZERO));
Ok(typed_json(&domain, "Message", &MESSAGE_FIELDS, &json!({ "msg": msg })))
}
pub fn decimal_text(units: U256, decimals: u8) -> Result<String, VerificationError> {
let step = U256::from(10u8).pow(U256::from(decimals.saturating_sub(6)));
if !(units % step).is_zero() {
return Err(differs(details::AMOUNT));
}
Ok(Amount::new(units).format_units(decimals))
}
const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1;
fn positive_time(value: u64) -> Result<u64, VerificationError> {
if (1..=MAX_SAFE_INTEGER).contains(&value) { Ok(value) } else { Err(differs(details::NONCE)) }
}
fn safe_salt(salt: u64) -> Result<u64, VerificationError> {
if salt <= MAX_SAFE_INTEGER { Ok(salt) } else { Err(differs(details::SALT)) }
}
fn is_client_id(id: &str) -> bool {
(1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric())
}
fn micros_nonce(nonce: u64) -> Result<u64, VerificationError> {
if (1_000_000_000_000_000..10_000_000_000_000_000).contains(&nonce) {
Ok(nonce)
} else {
Err(differs(details::NONCE))
}
}
fn at_seconds(seconds: u64) -> Result<DateTime<Utc>, VerificationError> {
i64::try_from(seconds)
.ok()
.and_then(|seconds| DateTime::from_timestamp(seconds, 0))
.ok_or(differs(details::NONCE))
}
fn at_millis(millis: u64) -> Result<DateTime<Utc>, VerificationError> {
i64::try_from(millis)
.ok()
.and_then(DateTime::from_timestamp_millis)
.ok_or(differs(details::NONCE))
}
fn at_micros(micros: u64) -> Result<DateTime<Utc>, VerificationError> {
i64::try_from(micros)
.ok()
.and_then(DateTime::from_timestamp_micros)
.ok_or(differs(details::NONCE))
}
fn domain_json(name: &str, chain_id: u64, contract: Option<Address>) -> Value {
let mut domain = json!({ "name": name, "version": "1", "chainId": chain_id });
if let Some(contract) = contract {
domain["verifyingContract"] = json!(format!("{contract:#x}"));
}
domain
}
fn typed_json(domain: &Value, primary: &str, fields: &[(&str, &str)], message: &Value) -> Value {
let props = |fields: &[(&str, &str)]| -> Vec<Value> {
fields.iter().map(|(name, kind)| json!({ "name": name, "type": kind })).collect()
};
let domain_fields = if domain.get("verifyingContract").is_some() {
&DOMAIN_FIELDS[..]
} else {
&DOMAIN_FIELDS[..3]
};
json!({
"types": { "EIP712Domain": props(domain_fields), primary: props(fields) },
"primaryType": primary,
"domain": domain,
"message": message,
})
}
#[cfg(test)]
mod tests;