use alloy_dyn_abi::TypedData;
use alloy_primitives::{Address, B256, U256};
use chrono::{DateTime, Duration, Utc};
use serde_json::{Map, Value};
use super::{
aster,
checks::{
deadline_within,
details::{self, at, changed, deployment, differs, stale, unsupported},
escrow,
take::{self, TakeIntent, TakeReads},
withdrawal,
},
eip712::{self, CloseOrders, FundOffer, Message, PayTake, Permit, QuoteSet},
relay,
signing::Verified,
};
use crate::{
api::{MoveRecipient, MoveRequest},
deployments::{self, ESCROWS, VENUE_DOMAINS},
error::VerificationError,
flows::BridgeTerms,
model::{Destination, Dex, Fill, TakePreparation, ToSign, ToSignKind, TransferIntent},
types::{Amount, EscrowEnvironment, MaxParts, VenueId},
};
pub const LIGHTER_CHAIN_ID: u64 = deployments::LIGHTER.id;
pub const LIGHTER_API: &str = crate::transport::LIGHTER_API;
pub const TAKER_API_KEY: u8 = deployments::slots(EscrowEnvironment::Production).lighter_key_index;
pub const TAKER_API_KEYS: [u8; 2] = [
deployments::slots(EscrowEnvironment::Production).lighter_key_index,
deployments::slots(EscrowEnvironment::Development).lighter_key_index,
];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct RelayPins {
pub depository: Address,
pub hyperliquid_depository: Address,
pub router: Address,
pub solver: Address,
pub solver_chain_id: &'static str,
}
pub const RELAY: RelayPins = RelayPins {
depository: relay::DEPOSITORY,
hyperliquid_depository: relay::HYPERLIQUID_DEPOSITORY,
router: relay::ROUTER,
solver: relay::SOLVER,
solver_chain_id: relay::SOLVER_CHAIN_ID,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct VenueDeposits {
pub gmx: Address,
pub gmx_vault: Address,
pub relay_credit: Address,
}
pub const VENUE_DEPOSITS: VenueDeposits = VenueDeposits {
gmx: relay::GMX_ROUTER,
gmx_vault: relay::GMX_VAULT,
relay_credit: relay::RELAY_CREDIT,
};
pub fn decimals_of(venue: &VenueId) -> Result<u8, VerificationError> {
deployments::chain(venue).map(|chain| chain.decimals).ok_or(unsupported(details::VENUE))
}
pub fn is_pinned_escrow(venue: &VenueId, contract: Address) -> bool {
let Some(chain) = deployments::chain(venue) else {
return false;
};
if deployments::is_venue_settled(venue) {
VENUE_DOMAINS.iter().any(|domain| domain.venue == *venue && domain.address == contract)
} else {
ESCROWS.iter().any(|escrow| escrow.chain_id == chain.id && escrow.address == contract)
}
}
pub fn require_signing_domains(items: &[ToSign]) -> Result<(), VerificationError> {
for (index, item) in items.iter().enumerate() {
let quote_set = item.kind == ToSignKind::QuoteSet;
if !quote_set && item.kind != ToSignKind::Fund && item.kind != ToSignKind::PayTake {
continue;
}
let domain = item.typed_data.get("domain");
let id = domain.and_then(|domain| domain.get("chainId")).and_then(Value::as_u64);
let contract = domain
.and_then(|domain| domain.get("verifyingContract"))
.and_then(Value::as_str)
.and_then(eip712::address_text);
let pinned = id.zip(contract).is_some_and(|(id, contract)| {
deployments::escrow_environment(id, contract).is_some()
|| (quote_set
&& VENUE_DOMAINS
.iter()
.any(|domain| domain.chain_id == id && domain.address == contract))
});
if !pinned {
return Err(at(deployment(details::ESCROW), index));
}
}
Ok(())
}
pub fn check_escrow_typed(
typed: &Value,
venue: &VenueId,
environment: EscrowEnvironment,
) -> Result<(), VerificationError> {
match typed.get("primaryType").and_then(Value::as_str) {
Some("QuoteSet") => {
escrow::check_escrow_typed::<QuoteSet>(typed, venue, environment)?;
}
Some("FundOffer") => {
escrow::check_escrow_typed::<FundOffer>(typed, venue, environment)?;
}
Some("PayTake") => {
escrow::check_escrow_typed::<PayTake>(typed, venue, environment)?;
}
Some("CloseOrders") => {
escrow::check_escrow_typed::<CloseOrders>(typed, venue, environment)?;
}
Some("Permit") => {
let chain = deployments::chain(venue).ok_or(unsupported(details::VENUE))?;
let domain = eip712::permit_domain(chain).ok_or(unsupported(details::VENUE))?;
let escrow =
deployments::escrow(chain.id, environment).ok_or(unsupported(details::VENUE))?;
if eip712::parse_in::<Permit>(typed, &domain)?.message.spender != escrow {
return Err(differs(details::SPENDER));
}
}
_ => return Err(differs(details::PRIMARY_TYPE)),
}
Ok(())
}
pub fn check_deadline(
deadline: U256,
seconds: i64,
now: DateTime<Utc>,
) -> Result<(), VerificationError> {
if deadline_within(deadline, now.timestamp(), seconds) {
Ok(())
} else {
Err(stale(details::DEADLINE))
}
}
const LOCK_PAYMENT_FIELDS: usize = 15;
pub fn take_payments(typed: &Value) -> Result<Vec<&Map<String, Value>>, VerificationError> {
let error = differs(details::PAYMENTS);
let payments = typed.pointer("/message/payments").and_then(Value::as_array).ok_or(error)?;
let payments = payments
.iter()
.map(|payment| payment.as_object().filter(|fields| fields.len() == LOCK_PAYMENT_FIELDS))
.collect::<Option<Vec<_>>>()
.ok_or(error)?;
if payments.is_empty() || payments.len() > usize::from(MaxParts::MAX.get()) {
return Err(error);
}
Ok(payments)
}
#[expect(
clippy::too_many_arguments,
reason = "the TypeScript checkTransfer, argument for argument"
)]
pub fn check_transfer(
typed: &Value,
venue: &VenueId,
signer: Address,
destination: Address,
amount: Amount,
send: bool,
now: DateTime<Utc>,
dex: Option<&Dex>,
) -> Result<Verified, VerificationError> {
if send {
withdrawal::check_send(typed, venue, signer, destination, amount, now, dex)
} else if typed.get("primaryType").and_then(Value::as_str) == Some("Op") {
Err(unsupported(details::PRIMARY_TYPE))
} else {
withdrawal::check_withdrawal(typed, venue, signer, destination, amount, now, dex)
}
}
pub fn check_aster_request(typed: &Value, chain_id: u64) -> Result<String, VerificationError> {
Ok(eip712::parse_in::<Message>(typed, &aster::domain(chain_id))?.message.msg)
}
pub fn aster_request(msg: &str, chain_id: u64) -> TypedData {
eip712::typed(&Message { msg: msg.to_owned() }, aster::domain(chain_id))
}
pub fn aster_transfer(typed: &Value) -> Result<aster::Transfer, VerificationError> {
Ok(take::aster_transfer(typed)?.1)
}
pub fn aster_amount(units: U256) -> Option<String> {
let decimals = deployments::ASTER.decimals;
let rounded = deployments::venue_units(units, &VenueId::Aster)?;
let unit = U256::from(10u8).pow(U256::from(decimals));
let fraction = (rounded % unit).to_string();
let fraction = format!("{fraction:0>width$}", width = usize::from(decimals));
let fraction = fraction.trim_end_matches('0');
let whole = rounded / unit;
Some(if fraction.is_empty() { whole.to_string() } else { format!("{whole}.{fraction}") })
}
pub fn check_aster_transfer(
transfer: &aster::Transfer,
fill: &Fill,
) -> Result<(), VerificationError> {
let owed = fill.amount_in.get();
let within = owed
.checked_add(deployments::ASTER.step())
.is_some_and(|limit| transfer.amount >= owed && transfer.amount < limit);
let ok = within
&& transfer.to == fill.maker_recipient
&& transfer.user == fill.payer
&& transfer.client_id == aster::client_id(fill.id);
if ok { Ok(()) } else { Err(differs(details::ASTER_TRANSFER)) }
}
pub fn check_take_intent(
prepared: &TakePreparation,
intent: &TakeIntent,
reads: TakeReads<'_>,
environment: EscrowEnvironment,
now: DateTime<Utc>,
) -> Result<Verified, VerificationError> {
if deployments::is_venue_settled(&intent.from) {
return Err(unsupported(details::VENUE));
}
take::check_take(prepared, intent, reads, environment, now)
}
pub fn check_lighter_take_intent(
prepared: &TakePreparation,
intent: &TakeIntent,
reads: TakeReads<'_>,
environment: EscrowEnvironment,
now: DateTime<Utc>,
) -> Result<Verified, VerificationError> {
if intent.from != VenueId::Lighter {
return Err(unsupported(details::VENUE));
}
take::check_take(prepared, intent, reads, environment, now)
}
pub fn check_aster_take_intent(
prepared: &TakePreparation,
intent: &TakeIntent,
reads: TakeReads<'_>,
environment: EscrowEnvironment,
now: DateTime<Utc>,
) -> Result<Verified, VerificationError> {
if intent.from != VenueId::Aster {
return Err(unsupported(details::VENUE));
}
take::check_take(prepared, intent, reads, environment, now)
}
pub fn check_route_intent(
first: &TransferIntent,
second: &TransferIntent,
hub: Address,
delivers: U256,
) -> Result<(), VerificationError> {
let then = first.then.as_ref().ok_or(changed(details::DESTINATION))?;
let same = second.previous_transfer_id == Some(first.id)
&& second.from == first.to
&& second.to == then.to
&& second.payer == hub
&& second.recipient == then.recipient
&& second.destination == then.destination.clone().unwrap_or(Destination::Venue)
&& second.max_fee_bps == then.max_fee_bps
&& second.withdrawal_preparation.is_none();
if !same {
return Err(changed(details::DESTINATION));
}
let (pays, planned) = (second.amount_in.get(), then.amount_in.get());
let share = then.min_out.get().checked_mul(pays).map(|scaled| scaled / planned);
let ok = !pays.is_zero()
&& pays <= delivers
&& pays.checked_mul(U256::from(100u8)).is_some_and(|hundred| hundred >= planned)
&& share.is_some_and(|share| second.min_out.get() >= share);
if ok { Ok(()) } else { Err(changed(details::AMOUNT)) }
}
pub fn bridge_expectation(
request: &MoveRequest,
recipient: MoveRecipient,
amount_in: Amount,
) -> crate::Result<BridgeTerms> {
BridgeTerms::for_move(request, recipient, amount_in)
}
pub fn check_bridge_order(
order: &Value,
expect: &BridgeTerms,
now: i64,
) -> Result<B256, VerificationError> {
relay::check_bridge_order(order, &expect.expectation(), now).map(|checked| checked.id)
}
pub fn bridge_send_asset(
amount: U256,
nonce: u64,
source_dex: Option<&str>,
) -> Result<TypedData, VerificationError> {
Ok(relay::bridge_send_asset(amount, nonce, source_dex)?.typed_data())
}
fn link_name(venue: &VenueId) -> Option<&'static str> {
match venue {
VenueId::Hyperliquid => Some("Hyperliquid"),
VenueId::Polymarket => Some("Polymarket Perps"),
VenueId::Lighter => Some("Lighter"),
VenueId::Aster => Some("Aster"),
VenueId::Gmx => Some("GMX"),
VenueId::Unknown(_) => None,
}
}
pub fn check_link_challenge(
message: &str,
nonce: &str,
expires_at: &str,
address: Address,
master: Address,
venue: &VenueId,
now: DateTime<Utc>,
) -> Result<Verified, VerificationError> {
let name = link_name(venue).ok_or(unsupported(details::VENUE))?;
let lines: Vec<&str> = message.split('\n').collect();
let expected = [
format!("LaMarge: link a {name} account"),
String::new(),
format!("Account: {address:#x}"),
format!("Master account: {master:#x}"),
format!("Nonce: {nonce}"),
format!("Expires: {expires_at}"),
];
let exact = lines.len() == expected.len()
&& lines.iter().zip(&expected).enumerate().all(|(index, (line, wanted))| {
if index == 2 || index == 3 {
line.eq_ignore_ascii_case(wanted)
} else {
*line == wanted.as_str()
}
});
if !exact {
return Err(differs(details::CHALLENGE));
}
let expires = DateTime::parse_from_rfc3339(expires_at)
.map_err(|_| differs(details::CHALLENGE))?
.with_timezone(&Utc);
if expires <= now || expires > now + Duration::minutes(10) {
return Err(stale(details::CHALLENGE_WINDOW));
}
Ok(Verified::text(message.to_owned(), address, Some(expires.timestamp())))
}
#[cfg(test)]
mod tests;