use std::collections::{BTreeSet, HashSet};
use alloy_primitives::{Address, B256, U256, hex};
use chrono::{DateTime, Utc};
use serde_json::Value;
use super::{
LighterOwners,
details::{self, at, changed, differs, stale, unsupported},
differs_unless, escrow, funding, signed, sum,
};
use crate::{
deployments,
error::VerificationError,
model::{
AsterTransferItem, Destination, Fill, FillRole, Funding, LighterTransferItem, Take,
TakePreparation, TakeSignRequest, ToSignKind, WalletFunding,
},
protocol::{
aster,
eip712::{self, Message, PayTake},
fees, lighter,
signing::Verified,
},
types::{Amount, Bps, EscrowEnvironment, MaxParts, VenueId},
};
const PAY_WINDOW_SECONDS: i64 = 90;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Delivery {
Account(Address),
Wallet(Address),
}
impl Delivery {
fn recipient(self) -> Address {
match self {
Self::Account(address) | Self::Wallet(address) => address,
}
}
fn wallet(self) -> bool {
matches!(self, Self::Wallet(_))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TakeIntent {
pub(crate) from: VenueId,
pub(crate) to: VenueId,
pub(crate) amount_in: Amount,
pub(crate) min_out: Amount,
pub(crate) max_parts: MaxParts,
pub(crate) max_fee_bps: Option<Bps>,
pub(crate) wallet_funding: bool,
pub(crate) delivery: Delivery,
pub(crate) payer: Address,
pub(crate) payer_account: Option<u64>,
pub(crate) at_once: bool,
pub(crate) route: bool,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct TakeReads<'a> {
pub(crate) lighter_owners: &'a LighterOwners,
pub(crate) wallet_funds: Option<&'a WalletFunding>,
}
pub(crate) fn check_take(
prepared: &TakePreparation,
intent: &TakeIntent,
reads: TakeReads<'_>,
environment: EscrowEnvironment,
now: DateTime<Utc>,
) -> Result<Verified, VerificationError> {
let take = &prepared.take;
if intent.delivery.wallet() && wallet_token(&intent.to).is_none() {
return Err(unsupported(details::DESTINATION));
}
let funding = if intent.wallet_funding { Funding::Wallet } else { Funding::Venue };
let funded = |value: &Option<Funding>| value.as_ref().unwrap_or(&Funding::Venue) == &funding;
if !funded(&take.funding) || !take.fills.iter().all(|fill| funded(&fill.funding)) {
return Err(differs(details::FUNDING));
}
let kind = payment_kind(&intent.from)?;
if !prepared.to_sign.iter().all(|item| *item.kind() == kind) {
return Err(differs(details::TO_SIGN_KIND));
}
check_minimum_received(take, intent)?;
if intent.to == VenueId::Lighter {
check_lighter_destination(&take.fills, intent.delivery.recipient(), reads.lighter_owners)?;
}
if intent.wallet_funding {
let funds = reads.wallet_funds.ok_or(changed(details::WALLET_FUNDS))?;
let spendable =
funding::check_wallet_funding(funds, &intent.from, intent.payer, environment, now)?;
if spendable < intent.amount_in.get() {
return Err(changed(details::WALLET_FUNDS));
}
}
let now = now.timestamp();
match &intent.from {
VenueId::Lighter => {
check_lighter_take(prepared, intent, reads.lighter_owners, environment, now)
}
VenueId::Aster => check_aster_take(prepared, intent, now),
_ => check_escrow_take(prepared, intent, environment, now),
}
}
pub(crate) fn lighter_accounts(prepared: &TakePreparation, intent: &TakeIntent) -> BTreeSet<u64> {
let mut indexes = BTreeSet::new();
if intent.to == VenueId::Lighter {
let delivered = prepared.take.fills.iter().filter_map(|fill| fill.delivery_to.as_deref());
indexes.extend(delivered.filter_map(account_index));
}
for item in &prepared.to_sign {
if let TakeSignRequest::Lighter(item) = item {
indexes.extend([item.typed_data.from_account_index, item.typed_data.to_account_index]);
}
}
indexes
}
pub(crate) fn aster_nonce(item: &AsterTransferItem) -> Result<u64, VerificationError> {
Ok(aster_transfer(&item.typed_data)?.1.nonce)
}
pub(crate) fn signable_until(prepared: &TakePreparation) -> Result<i64, VerificationError> {
let mut until = prepared.take.fills.iter().map(|fill| fill.pay_by.timestamp()).min();
if !prepared.aster_reissue {
for item in &prepared.to_sign {
if let TakeSignRequest::Aster(item) = item {
let ahead = nonce_seconds(aster_nonce(item)?) - aster::NONCE_AHEAD_SECONDS;
until = Some(until.map_or(ahead, |until| until.min(ahead)));
}
}
}
until.ok_or(differs(details::FILLS))
}
pub(crate) fn at_once_cutoff(prepared: &TakePreparation) -> Result<i64, VerificationError> {
Ok(signable_until(prepared)? - signed(deployments::AT_ONCE_SEND_MARGIN_SECONDS))
}
fn signing_bound(
prepared: &TakePreparation,
intent: &TakeIntent,
) -> Result<i64, VerificationError> {
let bound = if intent.at_once {
at_once_cutoff(prepared)? - signed(deployments::AT_ONCE_SIGNING_SECONDS)
} else {
signable_until(prepared)?
};
Ok(bound - 1)
}
fn nonce_seconds(nonce: u64) -> i64 {
signed(nonce / 1_000_000)
}
fn payment_kind(from: &VenueId) -> Result<ToSignKind, VerificationError> {
match from {
VenueId::Lighter => Ok(ToSignKind::LighterTransfer),
VenueId::Aster => Ok(ToSignKind::AsterTransfer),
VenueId::Hyperliquid | VenueId::Polymarket | VenueId::Gmx => Ok(ToSignKind::PayTake),
VenueId::Unknown(_) => Err(unsupported(details::VENUE)),
}
}
fn wallet_token(venue: &VenueId) -> Option<Address> {
deployments::chain(venue)?.wallet_token
}
fn account_index(text: &str) -> Option<u64> {
if !text.is_empty() && text.bytes().all(|b| b.is_ascii_digit()) {
text.parse().ok()
} else {
None
}
}
fn check_minimum_received(take: &Take, intent: &TakeIntent) -> Result<(), VerificationError> {
let error = differs(details::MINIMUM_RECEIVED);
let expected = if intent.delivery.wallet() {
let total = sum(take.fills.iter().map(|fill| fill.amount_out.get()), error)?;
let least = fees::minimum_received(&intent.to, total).ok_or(error)?;
Some((wallet_token(&intent.to).ok_or(error)?, least))
} else {
None
};
let served = take.minimum_received.as_ref().map(|least| (least.token, least.amount.get()));
if served == expected { Ok(()) } else { Err(error) }
}
fn check_lighter_destination(
fills: &[Fill],
recipient: Address,
owners: &LighterOwners,
) -> Result<(), VerificationError> {
let indexes: HashSet<Option<u64>> =
fills.iter().map(|fill| fill.delivery_to.as_deref().and_then(account_index)).collect();
let mut indexes = indexes.into_iter();
let (Some(Some(index)), None) = (indexes.next(), indexes.next()) else {
return Err(differs(details::FILLS_DELIVERY_TO));
};
if owners.get(&index) == Some(&recipient) {
Ok(())
} else {
Err(differs(details::DESTINATION_OWNER))
}
}
fn check_fill(fill: &Fill, intent: &TakeIntent) -> Result<(), VerificationError> {
let wallet = intent.delivery.wallet();
let destination = if wallet { Destination::Wallet } else { Destination::Venue };
differs_unless([
(fill.role == FillRole::Taker, details::FILLS_ROLE),
(fill.from_venue == intent.from, details::FILLS_FROM_VENUE),
(fill.to_venue == intent.to, details::FILLS_TO_VENUE),
(fill.payer == intent.payer, details::FILLS_PAYER),
(fill.taker_recipient == intent.delivery.recipient(), details::FILLS_TAKER_RECIPIENT),
(fill.destination == destination, details::FILLS_DESTINATION),
(fees::swap_fee(&fill.swap_id).wallet == wallet, details::FILLS_SWAP_ID),
(!fill.amount_in.get().is_zero(), details::FILLS_AMOUNT_IN),
])
}
fn check_delivery(fill: &Fill, recipient: Address) -> Result<(), VerificationError> {
let to = fill.delivery_to.as_deref();
let ok = match fill.to_venue {
VenueId::Aster => to.and_then(eip712::address_text) == Some(recipient),
VenueId::Lighter => to.and_then(account_index).is_some(),
_ => to.is_none(),
};
if ok { Ok(()) } else { Err(differs(details::FILLS_DELIVERY_TO)) }
}
fn check_windows(fill: &Fill, now: i64, pay_window: i64) -> Result<(), VerificationError> {
let (pay_by, t1) = (fill.pay_by.timestamp(), fill.t1.timestamp());
if pay_by <= now || pay_by > now + pay_window {
return Err(stale(details::FILLS_PAY_BY));
}
if t1 <= pay_by || t1 > now + signed(deployments::MAKER_TIMEOUT_SECONDS) + 30 {
return Err(differs(details::FILLS_T1));
}
Ok(())
}
fn check_escrow_take(
prepared: &TakePreparation,
intent: &TakeIntent,
environment: EscrowEnvironment,
now: i64,
) -> Result<Verified, VerificationError> {
let fills = &prepared.take.fills;
if fills.is_empty() || fills.len() > usize::from(intent.max_parts.get()) {
return Err(differs(details::FILLS));
}
if fills.iter().map(|fill| fill.id).collect::<HashSet<_>>().len() != fills.len() {
return Err(differs(details::FILLS_ID));
}
if fills.iter().map(|fill| fill.swap_id).collect::<HashSet<_>>().len() != fills.len() {
return Err(differs(details::FILLS_SWAP_ID));
}
let total_in = sum(fills.iter().map(|fill| fill.amount_in.get()), differs(details::AMOUNT_IN))?;
let total_out =
sum(fills.iter().map(|fill| fill.amount_out.get()), differs(details::AMOUNT_OUT))?;
if total_in.is_zero() || total_in > intent.amount_in.get() {
return Err(differs(details::AMOUNT_IN));
}
if total_out < intent.min_out.get() {
return Err(differs(details::AMOUNT_OUT));
}
let [TakeSignRequest::Typed(item)] = &prepared.to_sign[..] else {
return Err(differs(details::TO_SIGN));
};
let (parsed, domain) =
escrow::check_escrow_typed::<PayTake>(&item.typed_data, &intent.from, environment)?;
let pay = &parsed.message;
if item.signer != intent.payer || pay.payer != intent.payer {
return Err(differs(details::PAYER));
}
if !item.fill_id.is_some_and(|id| fills.iter().any(|fill| *fill.id.as_uuid() == id)) {
return Err(differs(details::FILL_ID));
}
if pay.payments.len() != fills.len() {
return Err(differs(details::PAYMENTS));
}
let receive = Receive::of(&intent.to, intent.delivery.wallet(), environment)?;
let pay_window = if intent.at_once || intent.route {
signed(deployments::ROUTE_PAY_WINDOW_SECONDS)
} else {
PAY_WINDOW_SECONDS
};
for (index, fill) in fills.iter().enumerate() {
check_paid_fill(fill, pay, intent, &receive, now, pay_window)
.map_err(|error| at(error, index))?;
}
if pay.deposit > total_in {
return Err(differs(details::DEPOSIT));
}
let not_after = signing_bound(prepared, intent)?;
Verified::typed(eip712::typed(pay, domain), parsed.digest, intent.payer, Some(not_after))
}
struct Receive {
chain_id: U256,
token: Address,
escrow: Address,
}
impl Receive {
fn of(
to: &VenueId,
wallet: bool,
environment: EscrowEnvironment,
) -> Result<Self, VerificationError> {
let chain = deployments::chain(to).ok_or(unsupported(details::VENUE))?;
let token = if wallet { chain.wallet_token } else { Some(chain.token) };
Ok(Self {
chain_id: U256::from(chain.id),
token: token.ok_or(unsupported(details::DESTINATION))?,
escrow: deployments::contract(to, environment).ok_or(unsupported(details::VENUE))?,
})
}
}
fn check_paid_fill(
fill: &Fill,
pay: &PayTake,
intent: &TakeIntent,
receive: &Receive,
now: i64,
pay_window: i64,
) -> Result<(), VerificationError> {
check_fill(fill, intent)?;
if fill.amount_out.get().is_zero() {
return Err(differs(details::FILLS_AMOUNT_OUT));
}
check_delivery(fill, intent.delivery.recipient())?;
check_windows(fill, now, pay_window)?;
let (t1, t2) = (fill.t1.timestamp(), fill.t2.timestamp());
if t2 <= t1 || t2 > now + signed(deployments::TAKER_TIMEOUT_SECONDS) + 30 {
return Err(differs(details::FILLS_T2));
}
let mut matching = pay.payments.iter().filter(|payment| payment.swapId == fill.swap_id);
let (Some(payment), None) = (matching.next(), matching.next()) else {
return Err(differs(details::PAYMENTS_SWAP_ID));
};
let (amount_in, amount_out) = (fill.amount_in.get(), fill.amount_out.get());
let dex = payment.dex == 0 || intent.from == VenueId::Hyperliquid && payment.dex == u32::MAX;
differs_unless([
(payment.payer == intent.payer, details::PAYMENTS_PAYER),
(payment.recipient == fill.maker_recipient, details::PAYMENTS_RECIPIENT),
(payment.hashlock == fill.hashlock, details::PAYMENTS_HASHLOCK),
(payment.amount == amount_in, details::PAYMENTS_AMOUNT),
])?;
fees::check_fee(
&fill.swap_id,
fill.taker_fee.get(),
amount_in,
amount_out,
false,
intent.max_fee_bps,
)?;
differs_unless([
(i64::try_from(payment.refundAt).ok() == Some(t2), details::PAYMENTS_REFUND_AT),
(
payment.deadline == U256::try_from(fill.pay_by.timestamp()).unwrap_or(U256::MAX),
details::PAYMENTS_DEADLINE,
),
(dex, details::PAYMENTS_DEX),
(payment.orderId == *fill.order_id.as_b256(), details::PAYMENTS_ORDER_ID),
(payment.sequence == fill.sequence, details::PAYMENTS_SEQUENCE),
(payment.amountOut == amount_out, details::PAYMENTS_AMOUNT_OUT),
(
payment.receiveRecipient == intent.delivery.recipient(),
details::PAYMENTS_RECEIVE_RECIPIENT,
),
(
payment.receiveChainId == receive.chain_id
&& payment.receiveToken == receive.token
&& payment.receiveEscrow == receive.escrow,
details::PAYMENTS_RECEIVE,
),
])
}
fn check_venue_fill<'a>(
prepared: &'a TakePreparation,
intent: &TakeIntent,
signer: Address,
fill_id: &uuid::Uuid,
now: i64,
) -> Result<&'a Fill, VerificationError> {
let ([fill], [_]) = (&prepared.take.fills[..], &prepared.to_sign[..]) else {
return Err(differs(details::TO_SIGN));
};
if signer != intent.payer {
return Err(differs(details::TO_SIGN_SIGNER));
}
check_fill(fill, intent)?;
if fill.id.as_uuid() != fill_id {
return Err(differs(details::FILL_ID));
}
if fill.amount_in > intent.amount_in {
return Err(differs(details::FILLS_AMOUNT_IN));
}
if fill.amount_out < intent.min_out {
return Err(differs(details::FILLS_AMOUNT_OUT));
}
fees::check_fee(
&fill.swap_id,
fill.taker_fee.get(),
fill.amount_in.get(),
fill.amount_out.get(),
true,
intent.max_fee_bps,
)?;
check_delivery(fill, intent.delivery.recipient())?;
check_windows(fill, now, PAY_WINDOW_SECONDS)?;
Ok(fill)
}
fn check_lighter_take(
prepared: &TakePreparation,
intent: &TakeIntent,
owners: &LighterOwners,
environment: EscrowEnvironment,
now: i64,
) -> Result<Verified, VerificationError> {
let Some(TakeSignRequest::Lighter(LighterTransferItem {
signer,
fill_id,
typed_data: terms,
..
})) = prepared.to_sign.first()
else {
return Err(differs(details::TO_SIGN));
};
let fill = check_venue_fill(prepared, intent, *signer, fill_id.as_uuid(), now)?;
let memo = lighter::fill_memo(fill.id);
if Some(terms.from_account_index) != intent.payer_account
|| terms.amount != fill.amount_in
|| terms.memo != hex::encode(memo)
{
return Err(differs(details::LIGHTER_TRANSFER));
}
if terms.api_key_index != deployments::slots(environment).lighter_key_index {
return Err(differs(details::LIGHTER_KEY));
}
if terms.usdc_fee.get() > deployments::LIGHTER_MAX_TAKER_FEE {
return Err(differs(details::LIGHTER_FEE));
}
if owners.get(&terms.to_account_index) != Some(&fill.maker_recipient) {
return Err(differs(details::LIGHTER_MAKER_ACCOUNT));
}
if owners.get(&terms.from_account_index) != Some(&intent.payer) {
return Err(differs(details::LIGHTER_PAYER_ACCOUNT));
}
let units = |amount: Amount| {
u64::try_from(amount.get()).map_err(|_| differs(details::LIGHTER_TRANSFER))
};
let transfer = lighter::Transfer {
nonce: terms.nonce,
from: terms.from_account_index,
from_route: lighter::COLLATERAL_ROUTE,
api_key: terms.api_key_index,
to: terms.to_account_index,
to_route: lighter::COLLATERAL_ROUTE,
asset: lighter::USDC_ASSET,
amount: units(terms.amount)?,
fee: units(terms.usdc_fee)?,
memo,
};
let not_after = signing_bound(prepared, intent)?;
let message = lighter::transfer_message(&transfer, deployments::LIGHTER.id);
Ok(Verified::text(message, intent.payer, Some(not_after)))
}
fn check_aster_take(
prepared: &TakePreparation,
intent: &TakeIntent,
now: i64,
) -> Result<Verified, VerificationError> {
let Some(TakeSignRequest::Aster(item)) = prepared.to_sign.first() else {
return Err(differs(details::TO_SIGN));
};
let fill = check_venue_fill(prepared, intent, item.signer, item.fill_id.as_uuid(), now)?;
let (msg, transfer, digest) = aster_transfer(&item.typed_data)?;
let owed = fill.amount_in.get();
let amount = transfer.amount >= owed && transfer.amount - owed < deployments::ASTER.step();
if !amount
|| transfer.to != fill.maker_recipient
|| transfer.user != intent.payer
|| transfer.client_id != aster::client_id(fill.id)
{
return Err(differs(details::ASTER_TRANSFER));
}
let window = aster::transfer_nonce_window(now, fill.pay_by.timestamp());
if !window.contains(&i128::from(transfer.nonce)) {
return Err(stale(details::ASTER_NONCE));
}
let ahead = nonce_seconds(transfer.nonce) - aster::NONCE_AHEAD_SECONDS;
let not_after = signing_bound(prepared, intent)?.min(ahead - 1);
let domain = aster::domain(aster::TRANSFER_CHAIN_ID);
let message = Message { msg };
Verified::typed(eip712::typed(&message, domain), digest, intent.payer, Some(not_after))
}
fn aster_transfer(raw: &Value) -> Result<(String, aster::Transfer, B256), VerificationError> {
let parsed = eip712::parse_in::<Message>(raw, &aster::domain(aster::TRANSFER_CHAIN_ID))?;
let msg = parsed.message.msg;
let transfer = aster::parse_transfer(&msg).ok_or(differs(details::ASTER_TRANSFER))?;
Ok((msg, transfer, parsed.digest))
}
#[cfg(test)]
mod tests;