lamarge 0.5.1

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
//! Withdrawal and send checks: Hyperliquid `SendAsset`, Polymarket `Withdraw` and internal
//! transfers, Aster transfers between accounts.

use alloy_primitives::{Address, U256};
use chrono::{DateTime, Utc};
use serde_json::Value;

use super::{
    SKEW_SECONDS,
    details::{self, differs, stale, unsupported},
    differs_unless, near_clock, signed,
};
use crate::{
    deployments,
    error::VerificationError,
    protocol::{
        aster,
        eip712::{self, Message, Withdraw},
        hyperliquid::{self, SendAsset},
        polymarket,
        signing::Verified,
    },
    types::{Amount, VenueId},
};

/// Checks a withdrawal (`POST /v1/withdrawals/prepare`) of exactly `amount` from `signer`'s
/// account on `venue` to `destination` at `at`: on Hyperliquid to the signer's own HyperEVM
/// address through USDC's bridge, on Polymarket to `destination`, without fee. Aster's
/// withdrawals (`Action`) are not supported.
pub(crate) fn check_withdrawal(
    raw: &Value,
    venue: &VenueId,
    signer: Address,
    destination: Address,
    amount: Amount,
    at: DateTime<Utc>,
) -> Result<Verified, VerificationError> {
    let amount = positive(amount)?;
    match venue {
        VenueId::Hyperliquid => {
            let (parsed, not_after) = check_send_asset(raw, amount, at)?;
            let send = &parsed.message;
            if destination != signer
                || !send
                    .destination
                    .eq_ignore_ascii_case(&format!("{:#x}", deployments::HYPERLIQUID_BRIDGE))
            {
                return Err(differs(details::DESTINATION));
            }
            if !["", "spot"].contains(&send.source_dex.as_str()) {
                return Err(differs(details::SOURCE_DEX));
            }
            if send.destination_dex != "spot" {
                return Err(differs(details::DESTINATION_DEX));
            }
            Verified::typed(send.typed_data(), parsed.digest, signer, not_after)
        }
        VenueId::Polymarket => {
            let domain = polymarket::withdraw_domain();
            let parsed = eip712::parse_in::<Withdraw>(raw, &domain)?;
            let withdraw = &parsed.message;
            differs_unless([
                (withdraw.account == signer, details::ACCOUNT),
                (withdraw.token == deployments::POLYMARKET.token, details::TOKEN),
                (withdraw.to == destination, details::TO),
                (withdraw.amount == amount, details::AMOUNT),
                (withdraw.fee.is_zero(), details::FEE),
            ])?;
            let not_after = near_clock(signed(withdraw.ts), at.timestamp(), details::TS)?;
            Verified::typed(eip712::typed(withdraw, domain), parsed.digest, signer, Some(not_after))
        }
        _ => Err(unsupported(details::VENUE)),
    }
}

/// Checks a send (`POST /v1/withdrawals/prepare` with a recipient) of exactly `amount` from
/// `signer`'s account on `venue` to `recipient`, another account of the same venue, at `at`. A
/// Polymarket wallet shows only the operation's hash: it is rebuilt from the typed data's `op`,
/// whose terms are checked.
pub(crate) fn check_send(
    raw: &Value,
    venue: &VenueId,
    signer: Address,
    recipient: Address,
    amount: Amount,
    at: DateTime<Utc>,
) -> Result<Verified, VerificationError> {
    let amount = positive(amount)?;
    if recipient == signer {
        return Err(differs(details::RECIPIENT));
    }
    match venue {
        VenueId::Polymarket => check_polymarket_send(raw, signer, recipient, amount, at),
        VenueId::Hyperliquid => {
            let (parsed, not_after) = check_send_asset(raw, amount, at)?;
            let send = &parsed.message;
            if send.destination != format!("{recipient:#x}")
                || hyperliquid::is_system_address(&send.destination)
            {
                return Err(differs(details::DESTINATION));
            }
            if !["", "spot"].contains(&send.source_dex.as_str()) {
                return Err(differs(details::SOURCE_DEX));
            }
            if !["", "spot"].contains(&send.destination_dex.as_str()) {
                return Err(differs(details::DESTINATION_DEX));
            }
            Verified::typed(send.typed_data(), parsed.digest, signer, not_after)
        }
        VenueId::Aster => {
            let domain = aster::domain(aster::TRANSFER_CHAIN_ID);
            let parsed = eip712::parse_in::<Message>(raw, &domain)?;
            let transfer = aster::parse_transfer(&parsed.message.msg)
                .ok_or(differs(details::ASTER_TRANSFER))?;
            // A send's own id: an `s` and 32 lowercase hex digits, never a fill's or a margin
            // move's.
            let id = transfer.client_id.strip_prefix('s').is_some_and(|hex| {
                hex.len() == 32
                    && hex.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
            });
            differs_unless([
                (transfer.user == signer, details::USER),
                (transfer.to == recipient, details::TO_ADDRESS),
                (id, details::CLIENT_TRAN_ID),
                (Some(transfer.amount) == deployments::venue_units(amount, venue), details::AMOUNT),
            ])?;
            // Microsecond-exact, unlike `near_clock`'s whole seconds.
            if !aster::nonce_near(transfer.nonce, at.timestamp(), SKEW_SECONDS) {
                return Err(stale(details::NONCE));
            }
            let not_after = Some(signed(transfer.nonce / 1_000_000).saturating_add(SKEW_SECONDS));
            Verified::typed(
                eip712::typed(&parsed.message, domain),
                parsed.digest,
                signer,
                not_after,
            )
        }
        _ => Err(unsupported(details::VENUE)),
    }
}

/// When a withdrawal or send was signed, from each venue's own unit: what a stored signature is
/// checked again at before it is submitted again.
pub(crate) fn signed_at(raw: &Value) -> Result<DateTime<Utc>, VerificationError> {
    let message = &raw["message"];
    let integer = |name: &str| {
        let value = &message[name];
        value.as_u64().or_else(|| value.as_str().and_then(|text| text.parse().ok()))
    };
    let seconds = match raw["primaryType"].as_str() {
        Some("Op") => integer("ts").map(|ms| ms / 1000),
        Some("HyperliquidTransaction:SendAsset") => integer("nonce").map(|ms| ms / 1000),
        Some("Message") => message["msg"]
            .as_str()
            .and_then(aster::parse_transfer)
            .map(|transfer| transfer.nonce / 1_000_000),
        Some("Withdraw") => integer("ts"),
        _ => None,
    };
    seconds
        .and_then(|seconds| DateTime::from_timestamp(signed(seconds), 0))
        .ok_or(differs(details::TYPED_DATA))
}

/// What a margin withdrawal of `venue` moves out of the account: Hyperliquid and Polymarket move
/// exactly the signed amount; any other venue is refused.
pub(crate) fn withdrawal_cost(raw: &Value, venue: &VenueId) -> Result<Amount, VerificationError> {
    let units = match venue {
        VenueId::Hyperliquid => {
            let parsed = eip712::parse::<SendAsset>(raw)?;
            deployments::decimal_units(&parsed.message.amount, deployments::HYPERLIQUID.decimals)
                .ok_or(differs(details::AMOUNT))?
        }
        VenueId::Polymarket => eip712::parse::<Withdraw>(raw)?.message.amount,
        _ => return Err(unsupported(details::VENUE)),
    };
    Ok(Amount::new(units))
}

fn positive(amount: Amount) -> Result<U256, VerificationError> {
    let units = amount.get();
    if units.is_zero() { Err(differs(details::AMOUNT)) } else { Ok(units) }
}

/// What every Hyperliquid `SendAsset` the SDK signs shares: USDC from the main account on
/// mainnet, exactly `amount`, its nonce within a minute of `at`. Returns it with its signing
/// bound.
fn check_send_asset(
    raw: &Value,
    amount: U256,
    at: DateTime<Utc>,
) -> Result<(eip712::Parsed<SendAsset>, Option<i64>), VerificationError> {
    let parsed = eip712::parse_in::<SendAsset>(raw, &hyperliquid::domain())?;
    let send = &parsed.message;
    let decimals = deployments::HYPERLIQUID.decimals;
    differs_unless([
        (send.hyperliquid_chain == "Mainnet", details::HYPERLIQUID_CHAIN),
        (send.token == deployments::HYPERLIQUID_USDC, details::TOKEN),
        (send.from_sub_account.is_empty(), details::FROM_SUB_ACCOUNT),
        (deployments::decimal_units(&send.amount, decimals) == Some(amount), details::AMOUNT),
    ])?;
    let not_after = near_clock(signed(send.nonce / 1000), at.timestamp(), details::NONCE)?;
    Ok((parsed, Some(not_after)))
}

/// A Polymarket internal transfer: the operation's `op` names the signer's account, pUSD, the
/// recipient and the amount, and its `data` is their hash.
fn check_polymarket_send(
    raw: &Value,
    signer: Address,
    recipient: Address,
    amount: U256,
    at: DateTime<Utc>,
) -> Result<Verified, VerificationError> {
    let domain = polymarket::operation_domain();
    let (parsed, op) = eip712::parse_operation(raw, &domain)?;
    let transfer = polymarket::InternalTransfer::read(op).ok_or(differs(details::OP))?;
    let decimals = deployments::POLYMARKET.decimals;
    differs_unless([
        (eip712::address_text(&transfer.account) == Some(signer), details::ACCOUNT),
        (
            eip712::address_text(&transfer.token) == Some(deployments::POLYMARKET.token),
            details::TOKEN,
        ),
        (eip712::address_text(&transfer.to) == Some(recipient), details::TO),
        (deployments::decimal_units(&transfer.amount, decimals) == Some(amount), details::AMOUNT),
        (transfer.hash() == Some(parsed.message.data), details::DATA),
    ])?;
    let not_after = near_clock(signed(parsed.message.ts / 1000), at.timestamp(), details::TS)?;
    Verified::typed(eip712::typed(&parsed.message, domain), parsed.digest, signer, Some(not_after))
}

#[cfg(test)]
mod tests;