lamarge 0.8.0

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
//! Escrow withdrawals and payment refunds: the escrow consents an owner or a maker signs outside
//! a take.

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! {
        /// An owner's withdrawal of an order's available balance.
        #[derive(Debug, PartialEq, Eq, serde::Serialize)]
        struct Withdrawal {
            address owner;
            bytes32 offerId;
            uint256 amount;
            bool toMargin;
            uint32 dex;
            uint256 nonce;
            uint256 deadline;
        }

        /// A maker's consent to give a locked payment back before its refund time.
        #[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);

/// How long a withdrawal signature may be good for, and the clock's margin.
const WITHDRAWAL_SECONDS: i64 = 3_600 + 60;
/// How long a refund consent may be good for.
const REFUND_SECONDS: i64 = 3_600;
/// Hyperliquid's spot balance as an escrow withdrawal's `dex`.
const HYPERLIQUID_SPOT: u32 = u32::MAX;

/// An escrow withdrawal as `POST /v1/escrow/withdraw/prepare` answers it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct EscrowWithdrawalPreparation {
    /// The master, for its order zero.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub owner: Option<Address>,
    /// The order's venue.
    pub venue: VenueId,
    /// The order.
    pub order_id: OrderId,
    /// In the venue's base units.
    pub amount: Amount,
    /// To the venue margin, or to the owner's wallet.
    pub to_margin: bool,
    /// Hyperliquid's destination: `0` perps, `4294967295` spot; `0` elsewhere.
    pub dex: u32,
    /// A random decimal integer.
    pub nonce: String,
    /// Unix seconds.
    pub deadline: u64,
    /// The one `escrow_withdrawal` to sign.
    pub to_sign: Vec<ToSign>,
}

/// A refund consent as `POST /v1/fills/{id}/refund/prepare` answers it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct PaymentRefundPreparation {
    /// Unix seconds: the consent is good until then.
    pub deadline: u64,
    /// The one `refund_payment` to sign.
    pub to_sign: Vec<ToSign>,
}

/// An escrow lock as `locks(owner, offerId, swapId)` returns it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct EscrowLock {
    /// What the lock holds.
    pub amount: U256,
    /// The claim's hashlock.
    pub hashlock: B256,
    /// Who claims it.
    pub recipient: Address,
    /// Unix seconds: the payer may take it back from then.
    pub refund_at: u64,
    /// 0 none, 1 locked, 2 claimed, 3 refunded.
    pub state: u8,
    /// Where a claim lands on the venue.
    pub dex: u32,
}

impl EscrowLock {
    /// A lock read from the escrow.
    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 }
    }
}

/// The dexes a withdrawal to `venue`'s margin may name: Hyperliquid's perps or spot, the one
/// account elsewhere.
fn margin_dexes(venue: &VenueId) -> &'static [u32] {
    match venue {
        VenueId::Hyperliquid => &[0, HYPERLIQUID_SPOT],
        _ => &[0],
    }
}

/// Checks one `escrow_withdrawal` of exactly `amount` by `order`'s owner, in the domain of
/// `chain`'s escrow as the API lists it (a pinned one), to the margin when `to_margin`, else to
/// the owner's wallet, good for an hour at most from `now`.
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)) };
    // An escrow venue's: a venue settled inside itself signs only quote sets.
    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))
}

/// Whether the maker of `fill`, abandoned inside its venue, may give the taker's locked payment
/// back before `t2`. From an escrow offer, the operator returns it at once.
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
}

/// Checks the one `refund_payment` consent of `fill`, signed by its payment's beneficiary in a
/// pinned escrow's domain on the paying chain, good until `t2` at most and an hour from `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),
    )
}

/// The escrow a refund consent on `venue` names: one pinned on `venue`'s chain, whichever
/// environment's.
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)),
    }
}

/// Checks the payment lock of `fill`, undelivered and delivered inside its venue: it still
/// refunds `fill.amount_in` to its payer at `t2`.
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;