use std::borrow::Cow;
use alloy_dyn_abi::DynSolValue;
use alloy_primitives::{Address, B256, U256};
use alloy_sol_types::{SolStruct, SolValue};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::{
deadline_bound, deadline_within,
deployment::check_registry,
details::{self, changed, deployment, differs, unsupported},
differs_unless, signed,
};
use crate::{
deployments,
error::VerificationError,
model::{EscrowChain, EscrowOrder, Fill, FillRole, MakerLeg, PaymentLeg, ToSign, ToSignKind},
protocol::{
eip712::{self, Schema},
signing::Verified,
},
types::{Amount, OrderId, VenueId},
};
mod schemas {
alloy_sol_types::sol! {
#[derive(Debug, PartialEq, Eq, serde::Serialize)]
struct Withdrawal {
address owner;
bytes32 offerId;
uint256 amount;
bool toMargin;
uint32 dex;
uint256 nonce;
uint256 deadline;
}
#[derive(Debug, PartialEq, Eq, serde::Serialize)]
struct RefundPayment {
address payer;
bytes32 swapId;
uint256 deadline;
}
}
}
use schemas::{RefundPayment, Withdrawal};
macro_rules! schema {
($($schema:ident),*) => {$(
impl Schema for $schema {
const PRIMARY: &'static str = <$schema as SolStruct>::NAME;
fn encode_type() -> Cow<'static, str> {
<$schema as SolStruct>::eip712_encode_type()
}
fn decode(value: &DynSolValue) -> Option<Self> {
<$schema as SolValue>::abi_decode(&value.abi_encode()).ok()
}
}
)*};
}
schema!(Withdrawal, RefundPayment);
const WITHDRAWAL_SECONDS: i64 = 3_600 + 60;
const REFUND_SECONDS: i64 = 3_600;
const HYPERLIQUID_SPOT: u32 = u32::MAX;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct EscrowWithdrawalPreparation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub owner: Option<Address>,
pub venue: VenueId,
pub order_id: OrderId,
pub amount: Amount,
pub to_margin: bool,
pub dex: u32,
pub nonce: String,
pub deadline: u64,
pub to_sign: Vec<ToSign>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct PaymentRefundPreparation {
pub deadline: u64,
pub to_sign: Vec<ToSign>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct EscrowLock {
pub amount: U256,
pub hashlock: B256,
pub recipient: Address,
pub refund_at: u64,
pub state: u8,
pub dex: u32,
}
impl EscrowLock {
pub fn new(
amount: U256,
hashlock: B256,
recipient: Address,
refund_at: u64,
state: u8,
dex: u32,
) -> Self {
Self { amount, hashlock, recipient, refund_at, state, dex }
}
}
fn margin_dexes(venue: &VenueId) -> &'static [u32] {
match venue {
VenueId::Hyperliquid => &[0, HYPERLIQUID_SPOT],
_ => &[0],
}
}
pub fn check_escrow_withdrawal(
prepared: &EscrowWithdrawalPreparation,
order: &EscrowOrder,
chain: &EscrowChain,
amount: Amount,
now: DateTime<Utc>,
to_margin: bool,
) -> Result<(), VerificationError> {
verified_escrow_withdrawal(prepared, order, chain, amount, now, to_margin).map(|_| ())
}
pub(crate) fn verified_escrow_withdrawal(
prepared: &EscrowWithdrawalPreparation,
order: &EscrowOrder,
chain: &EscrowChain,
amount: Amount,
now: DateTime<Utc>,
to_margin: bool,
) -> Result<Verified, VerificationError> {
let [item] = prepared.to_sign.as_slice() else { return Err(differs(details::TO_SIGN)) };
if check_registry(&order.venue, chain)?.is_none() {
return Err(unsupported(details::VENUE));
}
let domain = eip712::lamarge_domain(chain.id, chain.escrow);
let parsed = eip712::parse_in::<Withdrawal>(&item.typed_data, &domain)?;
let message = &parsed.message;
let dex_allowed = if to_margin {
margin_dexes(&order.venue).contains(&prepared.dex)
} else {
prepared.dex == 0
};
let now = now.timestamp();
let deadline = signed(prepared.deadline);
differs_unless([
(item.kind == ToSignKind::EscrowWithdrawal, details::KIND),
(item.signer == order.owner, details::SIGNER),
(message.owner == order.owner, details::OWNER),
(prepared.venue == order.venue, details::VENUE),
(prepared.order_id == order.order_id, details::ORDER_ID),
(message.offerId == *order.order_id.as_b256(), details::OFFER_ID),
(!amount.get().is_zero(), details::AMOUNT),
(prepared.amount == amount && message.amount == amount.get(), details::AMOUNT),
(message.toMargin == to_margin && prepared.to_margin == to_margin, details::TO_MARGIN),
(dex_allowed && message.dex == prepared.dex, details::DEX),
(message.nonce.to_string() == prepared.nonce, details::NONCE),
(message.deadline == U256::from(prepared.deadline), details::DEADLINE),
])?;
if deadline <= now || deadline > now.saturating_add(WITHDRAWAL_SECONDS) {
return Err(details::stale(details::DEADLINE));
}
Verified::typed(eip712::typed(message, domain), parsed.digest, order.owner, Some(deadline))
}
pub fn can_refund_payment(fill: &Fill, now: DateTime<Utc>) -> bool {
fill.role == FillRole::Maker
&& fill.maker_leg == MakerLeg::Abandoned
&& fill.payment_leg == PaymentLeg::Locked
&& fill.deliver_by.is_some()
&& fill.t2 > now
}
pub fn check_payment_refund(
fill: &Fill,
prepared: &PaymentRefundPreparation,
now: DateTime<Utc>,
) -> Result<(), VerificationError> {
verified_payment_refund(fill, prepared, now).map(|_| ())
}
pub(crate) fn verified_payment_refund(
fill: &Fill,
prepared: &PaymentRefundPreparation,
now: DateTime<Utc>,
) -> Result<Verified, VerificationError> {
if !can_refund_payment(fill, now) {
return Err(changed(details::REFUNDABLE));
}
let [item] = prepared.to_sign.as_slice() else { return Err(differs(details::TO_SIGN)) };
let escrow = refund_escrow(&item.typed_data, &fill.from_venue)?;
let chain = deployments::chain(&fill.from_venue).ok_or(unsupported(details::VENUE))?;
let domain = eip712::lamarge_domain(chain.id, escrow);
let parsed = eip712::parse_in::<RefundPayment>(&item.typed_data, &domain)?;
let message = &parsed.message;
differs_unless([
(item.kind == ToSignKind::RefundPayment, details::KIND),
(item.fill_id == Some(*fill.id.as_uuid()), details::FILL_ID),
(item.signer == fill.maker_recipient, details::SIGNER),
(message.payer == fill.payer, details::PAYER),
(message.swapId == fill.swap_id, details::SWAP_ID),
(message.deadline == U256::from(prepared.deadline), details::DEADLINE),
(signed(prepared.deadline) <= fill.t2.timestamp(), details::DEADLINE),
])?;
if !deadline_within(message.deadline, now.timestamp(), REFUND_SECONDS) {
return Err(details::stale(details::DEADLINE));
}
let not_after = deadline_bound(message.deadline);
Verified::typed(
eip712::typed(message, domain),
parsed.digest,
fill.maker_recipient,
Some(not_after),
)
}
pub(crate) fn refund_escrow(typed: &Value, venue: &VenueId) -> Result<Address, VerificationError> {
let chain = deployments::chain(venue).ok_or(unsupported(details::VENUE))?;
if deployments::is_venue_settled(venue) {
return Err(unsupported(details::VENUE));
}
let escrow = typed
.pointer("/domain/verifyingContract")
.and_then(Value::as_str)
.and_then(eip712::address_text)
.ok_or(differs(details::DOMAIN))?;
match deployments::escrow_environment(chain.id, escrow) {
Some(_) => Ok(escrow),
None => Err(deployment(details::ESCROW)),
}
}
pub fn check_refund_locks(fill: &Fill, payment: &EscrowLock) -> Result<(), VerificationError> {
if fill.deliver_by.is_none() {
return Err(unsupported(details::DELIVER_BY));
}
if fill.delivery_hash.is_some() {
return Err(changed(details::DELIVERY_HASH));
}
let holds = payment.state == 1
&& payment.amount == fill.amount_in.get()
&& payment.hashlock == fill.hashlock
&& payment.recipient == fill.maker_recipient
&& i64::try_from(payment.refund_at).is_ok_and(|at| at == fill.t2.timestamp());
if holds { Ok(()) } else { Err(changed(details::PAYMENT_LOCK)) }
}
#[cfg(test)]
mod tests;