use std::{borrow::Cow, ops::RangeInclusive};
use alloy_dyn_abi::{DynSolValue, TypedData};
use alloy_primitives::{Address, U256};
use alloy_sol_types::Eip712Domain;
use serde_json::json;
use super::eip712::{self, Schema};
use crate::{deployments, types::FillId};
pub const CHAIN_ID: u64 = 56;
pub const TRANSFER_CHAIN_ID: u64 = 1666;
pub(crate) const TOKEN: &str = "USDT";
pub(crate) const NONCE_AHEAD_SECONDS: i64 = 20;
const NONCE_LEAD_SECONDS: i64 = 70;
const MICROS: i128 = 1_000_000;
pub(crate) fn domain(chain_id: u64) -> Eip712Domain {
eip712::domain("AsterSignTransaction", "1", chain_id, Some(Address::ZERO))
}
const WITHDRAWAL_PRIMARY: &str = "Action";
const WITHDRAWAL_FIELDS: [(&str, &str); 8] = [
("type", "string"),
("destination", "address"),
("destination Chain", "string"),
("token", "string"),
("amount", "string"),
("fee", "string"),
("nonce", "uint256"),
("aster chain", "string"),
];
pub(crate) fn withdrawal_domain() -> Eip712Domain {
eip712::domain("Aster", "1", CHAIN_ID, Some(Address::ZERO))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Withdrawal {
pub(crate) kind: String,
pub(crate) destination: Address,
pub(crate) destination_chain: String,
pub(crate) token: String,
pub(crate) amount: String,
pub(crate) fee: String,
pub(crate) nonce: U256,
pub(crate) aster_chain: String,
}
impl Withdrawal {
pub(crate) fn typed_data(&self) -> TypedData {
eip712::custom_typed(
withdrawal_domain(),
WITHDRAWAL_PRIMARY,
&WITHDRAWAL_FIELDS,
json!({
"type": self.kind,
"destination": format!("{:#x}", self.destination),
"destination Chain": self.destination_chain,
"token": self.token,
"amount": self.amount,
"fee": self.fee,
"nonce": self.nonce.to_string(),
"aster chain": self.aster_chain,
}),
)
}
}
impl Schema for Withdrawal {
const PRIMARY: &'static str = WITHDRAWAL_PRIMARY;
fn encode_type() -> Cow<'static, str> {
eip712::custom_encode_type(WITHDRAWAL_PRIMARY, &WITHDRAWAL_FIELDS)
}
fn decode(value: &DynSolValue) -> Option<Self> {
let (_, _, values) = value.as_custom_struct()?;
let [kind, destination, destination_chain, token, amount, fee, nonce, aster_chain] = values
else {
return None;
};
let text = |value: &DynSolValue| value.as_str().map(str::to_owned);
Some(Self {
kind: text(kind)?,
destination: destination.as_address()?,
destination_chain: text(destination_chain)?,
token: text(token)?,
amount: text(amount)?,
fee: text(fee)?,
nonce: nonce.as_uint()?.0,
aster_chain: text(aster_chain)?,
})
}
}
pub(crate) fn fields<'a>(msg: &'a str, names: &[&str]) -> Option<Vec<&'a str>> {
let pairs: Vec<&str> = msg.split('&').collect();
if pairs.len() != names.len() {
return None;
}
pairs
.into_iter()
.zip(names)
.map(|(pair, name)| match pair.split_once('=') {
Some((key, value)) if key == *name && !value.contains('=') => Some(value),
_ => None,
})
.collect()
}
pub(crate) fn parse_nonce(text: &str) -> Option<u64> {
if text.len() == 16 && text.bytes().all(|b| b.is_ascii_digit()) {
text.parse().ok()
} else {
None
}
}
pub(crate) fn nonce_near(nonce: u64, now: i64, skew: i64) -> bool {
nonce_near_micros(nonce, i128::from(now) * MICROS, skew)
}
pub(crate) fn nonce_near_micros(nonce: u64, now: i128, skew: i64) -> bool {
(i128::from(nonce) - now).abs() <= i128::from(skew) * MICROS
}
pub(crate) fn transfer_nonce_window(now: i64, pay_by: i64) -> RangeInclusive<i128> {
let earliest = i128::from(now) + i128::from(NONCE_AHEAD_SECONDS);
let latest = (i128::from(now) + i128::from(NONCE_LEAD_SECONDS))
.max(i128::from(pay_by) + i128::from(NONCE_AHEAD_SECONDS));
earliest * MICROS..=latest * MICROS
}
pub fn client_id(fill: FillId) -> String {
fill.as_uuid().simple().to_string()
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Transfer {
pub amount: U256,
pub to: Address,
pub client_id: String,
pub nonce: u64,
pub user: Address,
}
pub(crate) fn parse_transfer(msg: &str) -> Option<Transfer> {
let names = ["asset", "amount", "toAddress", "clientTranId", "nonce", "user"];
let values = fields(msg, &names)?;
let [asset, amount, to, client_id, nonce, user] = values[..] else { return None };
if asset != TOKEN {
return None;
}
Some(Transfer {
amount: deployments::decimal_units(amount, deployments::ASTER.decimals)?,
to: eip712::address_text(to)?,
client_id: client_id.to_owned(),
nonce: parse_nonce(nonce)?,
user: eip712::address_text(user)?,
})
}
#[cfg(test)]
mod tests;